Search code examples
postgresqlvue.jsgraphqlloopbackopenapi

How to fix using loopback 4 (translate rest to graphql) : OPTIONS http://localhost:3001/graphql 405 (Method Not Allowed)


I am connecting the postgresql with loopback 4 and call the API on frontend using axios + restful and it was sucessfully done.

But when I tried to connect postgresql with loopback 4 and call the API on frontend using axios + graphql, it gives these 3 errors on browser's console:

  • OPTIONS http://localhost:3001/graphql 405 (Method Not Allowed)

  • Access to XMLHttpRequest at 'http://localhost:3001/graphql' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

  • Error: Network Error at createError (createError.js?2d83:16) at XMLHttpRequest.handleError (xhr.js?b50d:87)

I tried to search and read on googles, but most of them are not using loopback.

I followed this tutorial,

  1. https://v4.loopback.io/getting-started-oasgraph.html
  2. https://www.thepolyglotdeveloper.com/2019/01/query-graphql-api-vuejs-axios/

But still not resolved.

Here is my source code modification, Home.vue.

<template>
    <div>
    </div>
</template>

<script>
    import axios from "axios";
    export default {
        name: "HelloWorld",
        async mounted() {
            try {
                var result = await axios({
                    method: "POST",
                    url: "http://localhost:3001/graphql",
                    data: {
                        query: `
                            {
                                organizations {
                                  organizationId
                                  organizationName
                                }
                            }
                        `
                    }
                });
                console.log("kk", result);

            } catch (error) {
                console.error(error);
            }
        }
    }
</script>

<style scoped></style>

I expect the output inside console should be the API content. Is there any additional settings which I missed out?


Solution

  • This looks to me like the request is denied because of CORS.

    I checked the source code of oasgraph-cli, CORS is not allowed by default. Fortunately there is a CLI option to enable support for cross-origin requests.

    The following command should fix the problem for you:

    oasgraph --cors [path to saved OAS]
    

    The CLI option is defined here:

    .option('--cors', 'enable Cross-origin resource sharing (CORS)')
    

    And applies the following change to the Express application:

    if (program.cors) {
      app.use(cors());
    }