最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "blocked by CORS policy" when trying to redirect with expressJS - Stack Overflow

programmeradmin4浏览0评论

I have a problem when trying to redirect with ExpressJS, I made a login system that get a post request and if the user is exist the page suppose to redirect, but instead Cors is blocking it.

This is the request:

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
    };
})

This is the error it sends at the console:

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.

Can anyone tell whats the problem with that cors?

I have a problem when trying to redirect with ExpressJS, I made a login system that get a post request and if the user is exist the page suppose to redirect, but instead Cors is blocking it.

This is the request:

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
    };
})

This is the error it sends at the console:

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.

Can anyone tell whats the problem with that cors?

Share Improve this question asked Dec 4, 2019 at 11:37 SahiBalataSahiBalata 3532 gold badges6 silver badges15 bronze badges 1
  • Did you ever solve this? Same problem here. – Andrew Commented Oct 11, 2021 at 18:37
Add a ment  | 

3 Answers 3

Reset to default 3

For this, you need to send some header from the server so the browser will know the domain is allowed to access. You can try this
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 module:

//run this mand 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) => {

});

This is because CORS (Cross Origin Resource Sharing) is not allowed yet in your project. You can install cors package for this.

npm install cors

Then do this,

app.use(cors()) // It will enable all cors requests

That's it. You are good to go now. It is the simplest way to handle cors.

You can't call server server. from frontend. and redirect to service. That's just not allowed by CORS independently of the headers. You'll have to disable CORS pletely but that's a security risk I don't remend.

The solution is to make server. send the URL to frontend. and then redirect in the frontend using that info. Just don't use the request.redirect() option.

发布评论

评论列表(0)

  1. 暂无评论