【问题标题】:How to enable cors for apollo-server-lambda如何为 apollo-server-lambda 启用 cors
【发布时间】:2020-12-27 08:51:05
【问题描述】:

好的,我看到很多关于如何为 apollo-express 启用 cors 的答案,但我还没有找到真正适用于 apollo-server-lambda 的答案。

这是我从 chrome 得到的错误:

Access to XMLHttpRequest at 'https://5j3gae3086.execute-api.us-east-2.amazonaws.com/alpha/'
from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: The 'Access-Control-Allow-Origin' header
has a value 'https://example.com' that is not equal to the supplied origin.

我不知道如何更改值“https://example.com”。这是我如何尝试创建服务器的代码:

const { ApolloServer } = require('apollo-server-lambda')
const typeDefs = require('./schema')
const resolvers = require ('./resolvers')

const server = new ApolloServer({
    typeDefs,
    resolvers,
    introspection: true,
    playground: {
        endpoint: "/alpha/graphql",
    },
  });

exports.graphqlHandler = server.createHandler({
    cors: {
        // origin: true,
        origin: "http://localhost:4200", // <-- This is not changing the header value. Do I need to do it from the frontend?
        credentials: true,
    },
  });

我还需要在这里做什么?

编辑 我不确定这是否相关,但这是我的 graphql.module.ts 文件。这就是我在前端设置 grahql 的方式:

import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';

const uri = 'https://5j3gae3086.execute-api.us-east-2.amazonaws.com/alpha/'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  return {
    link: httpLink.create({ uri,
      // these comments are things that I tried with no luck :(
      // fetchOptions: {
      //   mode: 'no-cors',
      // },
      //  headers: {
      // 'Access-Control-Allow-Origin': 'http://localhost:4200',
      // 'Access-Control-Allow-Methods': 'POST',
      // 'Access-Control-Allow-Headers': 'application/json'
      // "Access-Control-Allow-Credentials" : true
      // "X-CSRFToken": Cookies.get('csrftoken')
    // },
  }),
    cache: new InMemoryCache(),
  };
}



@NgModule({
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule { }

另外,如果有人好奇,我正在使用 AWS Api Gateway 来使用 lambda,但我相信我已经正确添加了 cors 的配置。

我对此感到茫然。我需要改变什么?

【问题讨论】:

  • 对于对5j3gae3086.execute-api.us-east-2.amazonaws.com/alpha 的请求,服务器响应 502 Bad Gateway 错误。通过直接在浏览器中打开该 URL,您可以看到相同的错误。所以你没有 CORS 问题。修复 502 错误的原因,您可能会发现现有的 CORS 配置已经按预期工作。所以检查https://5j3gae3086.execute-api.us-east-2.amazonaws.com/alpha/服务器上的日志;该 502 错误似乎意味着它以某种方式代理另一台服务器,但未能成功连接到另一台服务器。日志会告诉你。
  • 哦,我只是在尝试修复它。让我将其恢复为工作状态
  • 好的,已经开始运行了。我可以从操场上获取查询,但是一旦我尝试从我的前端进行阿波罗查询,我就会收到问题中描述的错误。
  • 我刚刚在邮递员上试了一下,它按预期工作。我现在怀疑我的前端。

标签: aws-lambda cors apollo-client apollo-server apollo-angular


【解决方案1】:

按照此处的 CORS 设置说明,我可以成功使用 apollo-angular 返回简单查询的结果。不需要特殊的标题等。

https://www.apollographql.com/docs/apollo-server/deployment/lambda/

// serverless.yml
events:
  - http:
      path: graphql
      method: post
      cors: true
  - http:
      path: graphql
      method: get
      cors: true
// graphql.js
exports.graphqlHandler = server.createHandler({
  cors: {
    origin: '*',
    credentials: true,
  },
});
// graphql.module.ts
import {NgModule} from '@angular/core';
import {APOLLO_OPTIONS} from 'apollo-angular';
import {ApolloClientOptions, InMemoryCache} from '@apollo/client/core';
import {HttpLink} from 'apollo-angular/http';

const uri = 'https://xxx/dev/graphql';
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  return {
    link: httpLink.create({uri}),
    cache: new InMemoryCache(),
  };
}

@NgModule({
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

// In Angular 10
this.apollo
  .watchQuery({
    query: gql`
      {
        users {
          email
        }
      }
    `,
  })
  .valueChanges.subscribe(result => {
    console.log(result.data);
  });

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 2019-06-26
    • 2019-11-27
    • 2018-10-11
    • 2020-03-04
    • 2019-12-27
    • 2017-05-23
    • 2017-05-24
    • 2016-07-10
    相关资源
    最近更新 更多