CORS错误:上传到Lamda函数AWS时,甚至在API-Gateway和index.js文件中也启用了它

问题描述

我希望使用backend -login functionalityLamda function已经部署的frontend(S3-bucket)部署backend(RDS-MysqL)。提交包含登录详细信息的表单时出现错误,我也已在AWS API gateway中启用了CORS。我对AWS有点陌生,所以不确定在这里是否缺少任何内容。任何建议请在这里

  • Error in console

enter image description here

-index.js我在后端代码中有以下代码启用CORS


    app.use(
      cors({
        credentials: true,// for cookies
        origin: "*",optionsSuccessstatus: 200,})
    );

-api-gateway AWS我也在AWS中启用了CORS

enter image description here

上传Snippet of code from backend index.js

-Lamda function,这是第一次,因此我不确定我是否在下面的代码中正确编写了( before tweaking in below i used it locally and it worked fine the code)

// bring in express
const express = require("express");
const MysqLx = require("MysqL");
const jwt = require("jsonwebtoken");
const auth = require("./verifyTokenExisting");
const authNew = require("./verifyTokenNew");
const cors = require("cors");                // also using cors library here
const cookieParser = require("cookie-parser");
const pdf = require("html-pdf");
const pdfTemplate = require("./documents/pdfTemplate");
const fs = require("fs");
const { isContext } = require("vm");

const app = express();
app.use(express.json());
app.use(cookieParser());

app.use(
  cors({
    credentials: true,// for cookies
    origin: "*",})
);
// MysqL connection

let connection = MysqLx.createConnection({
  host: "database-x.xxxxxxxxxxx.eu-west-2.rds.amazonaws.com",user: "xxxx",password: "xxxxxxxxxxxx",database: "join_us",insecureAuth: true,});

////!  LOGIN & logoUT
exports.handler = (event,contect,callback) => {
  Context.callbackWaitsForEmptyEventLoop = false;
  //app.post("/api/newuser",(req,res) => {
  let x1 = event.body;
  console.log("144",x1);

  if (event.body.logout === false) {
    connection.query("SELECT * FROM  users WHERE email=?;",[x1.email],function (err,results) {
      
          if ((results[0].password == x1.password && results[0].userloginStatus == false) || (results[0].password == x1.password && results[0].userloginStatus == null)) {
            
            const payload = { email: results[0].email };
           // generate new token
            const token = jwt.sign(payload,"lllfasdgfdadsfasdfdasfcadsf");
            //below are the cookies sent to user first time when he log in
            callback(
              null,cookie("yogaoutlet_access_token",token,{
                maxAge: 25 * 24 * 60 * 60 * 1000,httpOnly: true,// it will enable on frotend-javascript to not have access to cokkies
                 
              })
            );

          
        } else callback(null,redirect("http://localhost:3000/about"));
      }

    
  } 

// if event.body.logout === true then logout the user
else {
    const payload = { email: event.body.email };
    console.log("339x",payload);
    const token = jwt.sign(payload,"lllfasdgfdadsfasdfdasfcadsf");

    callback(null,clearCookie("yogaoutlet_access_token"));
  }
  //});
};

解决方法

您在API Gateway中设置的COR(从屏幕截图中)仅用于OPTIONS方法。您还需要在GET,POST,PUT,DELETE方法中还返回“ Access-Control-Allow-Origin”。另外,您绝对不能使用通配符“ *”并将凭据设置为true。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

如果要通过代码返回CORS,则需要将方法设置为“使用Lambda代理集成”。否则,您需要将HTTP标头映射到stageVariable(通常),例如stageVariable.ORIGIN。我猜您可以将其映射到请求中的值,但是我认为映射到StageVariable较为安全,因此只有您已知的站点才能调用您的api。

关于Lambda代理集成的另一件事要注意,您的代码必须处理整个响应。我在Python中执行lambda,返回的结果如下:

return {
    'isBase64Encoded': 'false','statusCode': status_code,'headers': {
        'Content-Type': 'application/json','Access-Control-Allow-Origin': origin,'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token','Access-Control-Allow-Methods': 'GET,OPTIONS',},'body': json.dumps(resp)
}