如何使用Loopback 4(将REST转换为GraphQL)进行修复:选项http:// localhost:3001



我正在将postgresql与loopback 4连接起来,并使用Axios Restful在Frontend上调用API,并且可以成功完成。

但是,当我尝试将PostgreSQL与Loopback 4连接并使用Axios GraphQL在前端调用API时,它在浏览器的控制台上给出了这3个错误:

  • 选项http://localhost:3001/graphql 405(不允许的方法(

  • 在'http://localhost:3001/graphql'from Oncount'http://localhost:8081'访问XMLHTTPREQUEST:3001/GRAPHQL'已被CORS策略阻止:在请求的资源上没有"访问控制"标头。

  • 错误:网络错误在CreateRor(CreateRor.js?2d83:16(在xmlhttprequest.handleerror(xhr.js?b50d:87(

我试图在Google上搜索和阅读,但其中大多数没有使用loopback。

我遵循本教程,

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

但仍未解决。

这是我的源代码修改,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>

我希望控制台内部的输出应该是API内容。还有我错过的其他设置吗?

这对我来说看起来像是由于cors而被拒绝的。

我检查了oasgraph-cli的源代码,默认情况下不允许CORS。幸运的是,有一个CLI选项可以启用交叉原始请求的支持。

以下命令应为您解决问题:

oasgraph --cors [path to saved OAS]

CLI选项在此处定义:

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

并将以下更改应用于Express应用程序:

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

最新更新