关于node.js:NodeJs-Lambda-启用Cors

NodeJs - Lambda - Enable Cors

我在AWS上部署了一个nodejs lambda函数,该函数通过API网关公开了lambda端点。
端点在这里,允许您访问graphiql端点。

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

1
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的响应时-它不包含标头'Access-Control-Allow-Origin'

我在lambda.js中添加了以下内容以尝试启用cors,但似乎无法正常工作。

1
2
3
4
5
    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代码位于此处

是否有人对在我的nodejs函数上启用cors有什么想法?
我已在API网关上启用了cors


我不知道express-graphql的工作原理,但是如果它不返回而转发给下一个中间件app.user(cors()),它将永远不会受到攻击。 因为你要做的是

1
2
3
4
5
6
7
8
var app = express();
app.use('/', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
// then
app.user(cors())

在使用graphqlHTTP之类的方法之前,请尝试致电cors

1
2
3
4
5
6
7
var app = express();
app.use(cors());
app.use('/', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));