javascript - 尝试使用 expressJS 重定向时“被 CORS 策略阻止”
问题描述
我在尝试使用 ExpressJS 重定向时遇到问题,我创建了一个获取发布请求的登录系统,如果用户存在,则页面假设重定向,但 Cors 阻止了它。
这是请求:
router.post('/login', async (req, res) => {
try{
let usersData = await getFiles(__dirname + '/users.json');
let parsedUsers = JSON.parse(usersData);
let userChecker;
for(let i = 0; i < parsedUsers.length; i++){
if(parsedUsers[i].userName === req.body.userName){
userChecker = 1;
break;
}
}
if(!userChecker){
console.log(`${req.body.userName} Not exist`);}
else {
console.log(`${req.body.userName} Approved`);
res.redirect('/')
}
}
catch (err) {
if(err) throw err
};
})
这是它在控制台发送的错误:
Access to fetch at 'http://localhost:3001/users/login' (redirected from 'http://localhost:4000/users/login') from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
谁能告诉那个cors有什么问题?
解决方案
为此,您需要从服务器发送一些标头,以便浏览器知道该域被允许访问。你可以试试这个
Manual header
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
// your code
router.post('/login', async (req, res) => {
});
Cors npm 模块:
//run this command for install the cors module
npm install cors // install the cors
// use it in your code
app.use(cors()) // will enable cors
// your code
router.post('/login', async (req, res) => {
});
推荐阅读
- php - mysqli_multi_qry 在再次调用之前等待查询的输出
- python - Python 请求没有得到指定参数的正确页面
- r - 有没有办法用 ggplot2 做一个多堆栈条形图?
- react-native - 当我们过度解雇时如何保存文本输入值?
- javascript - 量角器:e2e:我有一个测试用例,我需要在其中测试该文本是否存在
- css - CSS 背景渐变动态动画
- swift - 无法理解 Apple Watch 并发症的生命周期并让它更新
- python - python - 如何在python中使用MTCNN从文件夹中的图像中提取人脸?
- uart - 如何使用 Atmega8 做硬件 UART
- mysql - 如何使用环境变量通过一个 docker-compose.yml 部署多个数据库?