gpt4 book ai didi

javascript - 尝试使用expressJS重定向时出现"blocked by CORS policy"

转载 作者:行者123 更新时间:2023-12-02 22:22:46 25 4
gpt4 key购买 nike

我在尝试使用 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有什么问题吗?

最佳答案

为此,您需要从服务器发送一些 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) => {

});

关于javascript - 尝试使用expressJS重定向时出现"blocked by CORS policy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com