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.