1

I have the following problem: I have an api running on localhost:3001 and a react application on localhost:3000. I can do requests with postman but when I use my website i get the following error:

Access to XMLHttpRequest at 'http://localhost:3001/login' from origin 'http://localhost:3000' 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.

I did some research and none of it worked.

https://www.html5rocks.com/en/tutorials/cors/ According to the website I need xhr.withCredentials = true. But this doesn't work either. Below are some code from my applications

function postAjax(method, apiUrl, data, callback) {
  let xhr = new XMLHttpRequest();
  xhr.open(method, apiUrl, true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.withCredentials = true;
  xhr.addEventListener("load", function() {
    if (xhr.status != 400 && xhr.status != 404) {
      callback(JSON.parse(xhr.responseText));
    }
  });
  xhr.send(JSON.stringify(data));
}

router.post('/login', function(req,rsp){
    const {username, password} = req.body;  
    req.db.get('select * from users where name=?', username, function(_err, user) {
        if(!user) {
            rsp.status(203).json({error:'User does not exist'})
        } else{
        let bcryptPassword = user.bcryptPassword;
        let level = user.level;
        let auth =  jwt.sign({username, level}, SECRET);
        if(bcrypt.compareSync(password, bcryptPassword)){
            rsp.header('auth', auth);
            rsp.status(200).json({token: auth})
        } else{
            rsp.status(203).json({error: 'Wrong password'});
        }
    }
    });
});

Does anybody know how to fix this problem and what the cause is? With if possible a little bit of example code.

Norstan
  • 39
  • 4

1 Answers1

2

You can use the cors module in your server. https://www.npmjs.com/package/cors npm i cors to install external cors package

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
Cuong Nguyen
  • 314
  • 2
  • 8
  • This. And to clear up any confusion, since Postman is not a browser, browser cross-origin restrictions do not apply, which is why API testing applications will be able to successfully complete the request while your browser cannot. – Jay Kariesch Oct 18 '19 at 22:34
  • Assuming OP is actually using express.js, that is – Lennholm Oct 19 '19 at 01:26