Dav*_*eAl 9 node.js cors graphql netlify nestjs
我目前正在尝试在 Google Cloud Run 上使用 Graphql 部署我的 NestJS 服务器。我还有一个作为客户端使用的 React 应用程序,托管在 Netlify 上。
但是,当我尝试运行此命令时,我在控制台中收到以下 CORS(跨源资源共享)错误:
Access to fetch at 'https://google-cloud.run.app/graphql' from origin 'https://myapp.netlify.app' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Run Code Online (Sandbox Code Playgroud)
我的 NestJS 应用程序配置如下:
// {cors: true}
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: true,
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
allowedHeaders: "Content-Type,Accept,Authorization,Access-Control-Allow-Origin"
});
Run Code Online (Sandbox Code Playgroud)
在另一篇 stackoverflow 文章中,我看到 GraphQL CORS 配置覆盖了 NestJS CORS 配置,因此我也将 CORS 逻辑添加到 GraphQL 中,app.module.ts
如下所示:
@Module({
controllers: [],
imports: [
...,
GraphQLModule.forRootAsync({
useFactory: (configService) => {
const playground = configService.get("GRAPHQL_PLAYGROUND");
const introspection = configService.get("GRAPHQL_INTROSPECTION");
return {
autoSchemaFile: true,
playground,
introspection: playground || introspection,
cors: {
credentials: true,
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
allowedHeaders: "Content-Type,Accept,Authorization,Access-Control-Allow-Origin"
},
context: ({req}) => {
return {req};
},
installSubscriptionHandlers: true
};
},
inject: [ConfigService],
imports: [ConfigModule]
}),
...
Run Code Online (Sandbox Code Playgroud)
当我从 运行客户端localhost
并且直接连接到 Google Cloud Run 容器时,此时一切正常,并且我没有收到任何 CORS 错误。我正在使用 Apollo GraphQL 客户端发出 API 请求。
然而,当我使用 Netlify 客户端时,我遇到了上述 CORS 问题。
关于如何解决这个问题有什么想法吗?这是 Netlify 的问题吗?这是 Google Cloud Run 问题吗?或者我是否缺少任何 CORS 标头?
归档时间: |
|
查看次数: |
4150 次 |
最近记录: |