【问题标题】:NodeJs - Lambda - Enable CorsNodeJs - Lambda - 启用 Cors
【发布时间】:2018-10-11 17:14:41
【问题描述】:

我在 aws 上部署了一个 nodejs lambda 函数,它通过 API Gateway 公开一个 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 的响应时 - 它不包含标题“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 Gateway 上启用了 cors

【问题讨论】:

    标签: node.js amazon-web-services cors aws-lambda apollo-server


    【解决方案1】:

    我不知道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,
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-26
      • 2020-12-27
      • 2021-06-24
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多