<分区>
我有以下问题: 我有一个在 localhost:3001 上运行的 api 和一个在 localhost:3000 上运行的 React 应用程序。我可以向 postman 提出请求,但是当我使用我的网站时,出现以下错误:
在“http://localhost:3001/login”访问 XMLHttpRequest '来自原产地' http://localhost:3000 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。
我做了一些研究,但没有任何效果。
https://www.html5rocks.com/en/tutorials/cors/ 根据网站,我需要 xhr.withCredentials = true。但这也不起作用。 以下是我的应用程序中的一些代码
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'});
}
}
});
});
有谁知道如何解决这个问题以及原因是什么?如果可能的话,使用一些示例代码。