首页 > 解决方案 > 尝试使用 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有什么问题?

标签: javascriptexpress

解决方案


为此,您需要从服务器发送一些标头,以便浏览器知道该域被允许访问。你可以试试这个
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) => {

});


推荐阅读