首页 > 解决方案 > 如何为 apollo-server-lambda 启用 cors

问题描述

好的,所以我看到了很多关于如何为 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 的配置。

aws cors 配置

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

标签: aws-lambdacorsapollo-clientapollo-serverapollo-angular

解决方案


按照此处的 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);
  });

推荐阅读