简体   繁体   English

CORS 错误:即使我在上传到 Lamda 时在 API 网关和我的 index.js 文件中启用它 function AWS

[英]CORS error: even i enable it at API-Gateway and in my index.js file when uploading to Lamda function AWS

i am looking to deploy the backend -login functionality using Lamda function i have already deployed frontend(S3-bucket) and backend(RDS-mysql) .我希望使用Lamda function部署backend -login functionality我已经部署了frontend(S3-bucket)backend(RDS-mysql) i am getting an error when i submit the form with login details, i have also enabled the CORS in AWS API gateway .当我提交带有登录详细信息的表单时出现错误,我还在 AWS API gateway中启用了 CORS。 I am a bit new to AWS so i am not sure if i am missing something here.我对 AWS 有点陌生,所以我不确定我是否遗漏了什么。 any suggestion please here.任何建议请在这里。

  • Error in console

在此处输入图像描述

- index.js i have below code to enable CORS in the backend code - index.js我有以下代码在后端代码中启用CORS


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

- API-Gateway AWS i enabled the CORS in AWS as well - API-Gateway AWS我也在 AWS 中启用了 CORS 在此处输入图像描述

- Snippet of code from backend index.js which i uploaded to Lamda function , this is the first time so i am not sure if i wrote the code below correct ( before tweaking in below i used it locally and it worked fine the code) - 我上传到Lamda function Snippet of code from backend index.js ,这是第一次,所以我不确定我是否在下面编写了正确的代码( 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: "*",
    optionsSuccessStatus: 200,
  })
);
// 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"));
  }
  //});
};

The CORs you setup in API Gateway (from your screenshot) is just for the OPTIONS method.您在 API 网关中设置的 CORs(来自您的屏幕截图)仅适用于 OPTIONS 方法。 You need to also return 'Access-Control-Allow-Origin' in your GET, POST, PUT, DELETE method as well.您还需要在 GET、POST、PUT、DELETE 方法中返回“Access-Control-Allow-Origin”。 Also, you definitely can't use wildcard, "*" and have credentials set to true.此外,您绝对不能使用通配符“*”并将凭据设置为 true。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

If you want to return the CORS via code, you will need to set your method to 'Use Lambda Proxy integration'.如果您想通过代码返回 CORS,您需要将方法设置为“使用 Lambda 代理集成”。 Otherwise you'll need to map an HTTP Header to a stageVariable (usually) eg stageVariable.ORIGIN.否则你需要 map HTTP Header 到 stageVariable(通常)例如 stageVariable.ORIGIN。 I guess you could map it to a value in the request, but I think it's safer to map to StageVariable so only your known sites can call your api.我想您可以将 map 转换为请求中的值,但我认为将 map 转换为 StageVariable 更安全,因此只有您已知的站点可以调用您的 api。

One more thing to note on the Lambda Proxy integration, your code has to handle the whole response.关于 Lambda 代理集成的另一件事需要注意,您的代码必须处理整个响应。 I do my lambdas in Python and my return looks like this:我在 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过AWS api-gateway返回一个Base64编码的zip文件供下载 - How do I return a Base64 encoded zip file through AWS api-gateway for download AWS API 网关资源中的“启用 CORS”? - "Enable CORS" in AWS API Gateway resource? 如何在 API 网关和 React 应用程序之间启用 AWS 中的 CORS 策略? - How to enable CORS policy in AWS between API Gateway and React app? AWS API 网关和授权方 CORS 错误 - AWS API gateway and authorizer CORS error CORS 仅 POST 请求错误:AWS HTTP API 网关 - CORS Error for Only POST request: AWS HTTP API Gateway AWS API Gateway + Lamda - 如何处理每秒 100 万个请求 - AWS API Gateway + Lamda - how to handle 1 million requests per second AWS API 网关:CORS 和空事件 Object - AWS API Gateway : CORS and Empty Event Object XMLHttpRequest 错误 flutter web [启用 CORS AWS API 网关] - XMLHttpRequest error in flutter web [Enabling CORS AWS API gateway] Firebase 云 function cors 即使添加 cors 中间件也会出错 - Firebase cloud function cors error even when adding cors middleware 云函数部署错误:加载用户代码时函数失败。 错误信息:无法加载文件 lib/index.js 中的代码 - Cloud functions deployment error: Function failed on loading user code. Error message: Code in file lib/index.js can't be loaded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM