Fix CORS “Response to preflight…” header not present with AWS API gateway and amplify

后端 未结 3 582
生来不讨喜
生来不讨喜 2021-01-18 00:13

I\'ve been struggling so long with the error below. I\'ve tried so many tutorials and stackoverflow answers and none of the solutions fixes my problem.

3条回答
  •  爱一瞬间的悲伤
    2021-01-18 00:49

    If Someone using serverless with nodejs and facing this issue of prelight with cors-policy, here is the simple solution ...

    functions:
      externalHandler:
        handler: handler.handlerExport
        events:
          - http:
              path: handlerPath
              method: post
              cors:
                origin: '*' # <-- Specify allowed origin
                headers: # <-- Specify allowed headers
                  - Content-Type
                  - X-Amz-Date
                  - Accept
                  - Authorization
                  - X-Api-Key
                  - X-Amz-Security-Token
                  - X-Amz-User-Agent
                allowCredentials: false
    

    inside the handler file

    if you are using express

    ...
    const app = express();
    app.use(function (req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Credentials", true);
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
      res.header(
        "Access-Control-Allow-Headers",
        "x-www-form-urlencoded, Origin, X-Requested-With, Content-Type, Accept, Authorization"
      );
      next();
    });
    ...
    

    or in general

      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': true,
        },
        body: JSON.stringify({
          product: product
        }),
      };
    

    for more information refer serverless article

提交回复
热议问题