在我们的 nodejs 应用程序中出现“Access-Control-Allow-Origin”错误
Posted
技术标签:
【中文标题】在我们的 nodejs 应用程序中出现“Access-Control-Allow-Origin”错误【英文标题】:Stuck in 'Access-Control-Allow-Origin' error in our nodejs app 【发布时间】:2021-09-12 06:43:52 【问题描述】:我们的 nodeJS 应用部署在 AWS-lambda,我们正在尝试请求身份验证,但在控制台中收到此错误
访问 XMLHttpRequest 在 'https://vklut41ib9.execute-api.ap-south-1.amazonaws.com/dev/api/auth/login' 来自原点“https://our-app.netlify.app”已被 CORS 阻止 政策:没有“Access-Control-Allow-Origin”标头出现在 请求的资源。
但奇怪的是,当我们尝试使用错误的凭据时,我们没有收到此错误
就在我们尝试使用真实凭据进行访问时,我们遇到了 cors 错误
我们的 app.js 代码:
const dotenv = require("dotenv");
const express = require("express");
const app = express();
const cors = require("cors");
const session = require("express-session");
const passport = require("passport");
const serverless = require("serverless-http");
// const http = require("http");
// var server = http.createServer(app);
dotenv.config( path: "./src/config/config.env" );
// files
const connectDb = require("./src/config/db");
const auth = require("./src/routes/apis/auth");
const user = require("./src/routes/apis/user");
// database connection
connectDb();
app.use(cors());
app.use(function (req, res, next)
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
);
app.use(express.json());
app.use(express.urlencoded( extended: false ));
// passport config
require("./src/config/passport")(passport);
// passport middleware
app.use(passport.initialize());
app.use(passport.session());
app.use(
session(
secret: "key",
resave: false,
saveUninitialized: false,
)
);
app.use("/api/auth", auth);
app.use("/api/users", user);
module.exports.handler = serverless(app);
我们的认证路线:
// auth route for login user
router.post("/login", async (req, res) =>
const workerId, workerPassword = req.body;
try
const foundUser = await User.findOne( workerId );
if (!foundUser)
return res.status(404).json(
message: "Employee does not exist (Invalid Employee ID)",
);
else if (foundUser.totalLoginAttemptLeft > 0)
const checkPasswordData = await checkPassword(workerPassword, foundUser);
if (!checkPasswordData.isMatch)
await passwordNotMatched(res, checkPasswordData.updatedWorker);
else
const jwtToken = await totalLogin(foundUser, reset);
return res.status(200).json( token: "Bearer " + jwtToken );
catch (error)
console.error(error.message);
return res.status(500).json( message: error.message );
);
令牌生成代码:
const jwt = require("jsonwebtoken");
// make jwt token
const makeToken = async (payload) =>
const jwtToken = jwt.sign(payload, process.env.SECRET_KEY,
expiresIn: "7d",
);
if (!jwtToken)
console.log(err);
return false;
return jwtToken;
;
module.exports = makeToken;
客户端登录处理
const loginUser = (loginInfo, loginType) => async (dispatch) =>
try
const baseUrlNode = await helperFunction.checkLoginType(
loginType
);
const loginSuccess = await axios.post(
`$baseUrlNode$api.Auth_Api.LOGIN_API`,
loginInfo
);
// console.log(loginSuccess);
const token = "" = loginSuccess.data;
const id, workerId, workerAadharCardNumber = jwt_decode(
token
);
if (id && workerId && workerAadharCardNumber && loginType)
await setLocalStorage(token, loginType);
setAuthToken(token);
const decoded = jwt_decode(token);
dispatch(setCurrentUser(decoded));
else
dispatch(setAuthLoading(false));
const errorData =
data: message: "Not able to login" ,
status: 400
;
dispatch(
type: types.AuthTypes.AUTH_GET_ERRORS,
payload: errorData
);
catch (loginError)
const errorData =
data: loginError.response.data,
status: loginError.response.status
;
dispatch(
type: types.AuthTypes.AUTH_GET_ERRORS,
payload: errorData
);
;
【问题讨论】:
你能看到响应头...x-amzn-errortype
- 这可能解释了问题 - 有一些“InternalServerErrorException”
@JaromandaX 是的 x-amzn-errortype 存在
【参考方案1】:
No 'Access-Control-Allow-Origin' header present 错误可能由于以下任何原因而发生:
方法类型(例如 GET、PUT 或 POST)未配置为返回所需的 CORS 标头。 API 未配置返回所需 CORS 标头的 OPTIONS 方法 具有代理集成或非代理集成的 API 未配置为返回所需的 CORS 标头。所以我建议添加此代码或仅使用允许方法类型(GET、POST、PUT 等)的部分更新您的代码
app.use((req, res, next) =>
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, 'Content-Type' : 'multipart/form-data' ,* "
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
);
另外,我推荐阅读这篇article
还有这个article2
【讨论】:
以上是关于在我们的 nodejs 应用程序中出现“Access-Control-Allow-Origin”错误的主要内容,如果未能解决你的问题,请参考以下文章
解决PyCharm上传代码到Github出现push failed: unable to acces
用于Azure B2C acces令牌的Exchange Facebook SDK acces令牌
nodejs 应用程序在本地运行良好会在 glitch.com 中出现错误