NodeJs - Lambda - 启用 Cors

NodeJs - Lambda - Enable Cors

我在 aws 上部署了一个 nodejs lambda 函数,它通过 API 网关公开了一个 lambda 端点。 端点是 here 并允许您访问 graphiql 端点。

当我尝试从我的 React 应用程序调用此端点时 - 我收到 cors 错误

Failed to load https://3h5e2m2b1a.execute-api.us-east-1.amazonaws.com/test?: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

在检查来自 Lambda 的响应时 - 它不包含 header 'Access-Control-Allow-Origin'

我在 lambda.js 中添加了以下内容以尝试启用 cors,但它似乎不起作用。

    const awsServerlessExpress = require('aws-serverless-express');
const app = require('./src/app');
const cors = require('cors');
app.use(cors()); // enable `cors` to set HTTP response header: Access-Control-Allow-Origin: *
const server = awsServerlessExpress.createServer(app);

我的 lambda 函数的 nodejs 代码位于 here

有人知道我需要做什么才能在我的 nodejs 函数上启用 cors 吗? 我在 API 网关

上启用了 cors

我不知道 express-graphql 是如何工作的,但如果它没有转发到下一个中​​间件就做出回应 app.user(cors()) 将永远不会被击中。因为你所做的是

var app = express();
app.use('/', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
// then
app.user(cors())

在使用 graphqlHTTP 类似

之前尝试调用 cors
var app = express();
app.use(cors());
app.use('/', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));