[英]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.