我在前端使用React js,在后端使用nodejs。我的应用程序在Chrome浏览器中工作正常,但在Mozilla Firefox浏览器中,它收到以下错误:
阻止跨源请求:同源策略禁止在http://192.168.1.195:5000/authenticate/读取远程资源。 (原因:在CORS预检频道的CORS标题'Access-Control-Allow-Headers'中遗漏了令牌'content-type'。)
Api是用Node js编写的,在POSTMAN中测试好了。 (另外,如果我从MOZILLA Firefox浏览器调用任何GET方法,我正确得到json响应)。
所以我猜这不是Node.js apis的问题。
对于CORS,我已经添加了以下代码:
app.use(function (req, res, next) {
res.setHeader('content-type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader("Access-Control-Allow-Headers", '*', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
示例jsx代码是:
ChkLogin(){
const email = this.refs.email.value;
const pwd = this.refs.password.value;
var auth;
var token;
var prev;
localStorage.setItem('email',this.refs.email.value);
let authURL= config.baseUrl+'/authenticate/';
fetch(authURL, {
method: 'POST',
headers : {'Content-Type':'application/json'},
body:JSON.stringify({'name':email, 'password':pwd})
}).then((res) => res.json())
.then((data) => {token=data[0].token;auth=data[0].auth;prev=data[0].prev;
console.log(data);
if(auth===true)
{
this.setState({prev});
localStorage.setItem('prev',this.state.prev);
this.setState({token});
localStorage.setItem('token',this.state.token);
this.props.history.push('/issue');
}
else {
alert("Invalid Login")
this.props.history.push('/');
}
})
.catch((err)=>console.log(err))
}
对应的node.js api
exports.authenticate = function (req,res) {
var response = [];
if (
typeof req.body.name !== 'undefined' &&
typeof req.body.password !== 'undefined'
) {
var name = req.body.name, password = req.body.password;
connection.query('SELECT * from user where user_username = ?', [name], function(err, rows, fields)
{
if (!err){
var response = [];
if (rows.length != 0)
{
console.log(rows[0]['user_password'])
console.log(md5(password))
if(rows[0]['user_password']===md5(password))
{
console.log(rows[0]['user_id']);
var token = jwt.sign({ id: rows[0]['user_id']}, tokenconfig.secret,
{
expiresIn: tokenconfig.tokenLife
});
var refreshToken = jwt.sign({ id: rows[0]['user_id']}, tokenconfig.refreshTokenSecret,
{
expiresIn: tokenconfig.refreshTokenLife
})
response.push({ auth: true, token: token, refreshToken: refreshToken, prev: rows[0]['user_prev'] });
tokenList[refreshToken] = response;
console.log(tokenList[refreshToken]);
} else {
response.push({'result' : 'error', 'msg' : 'Invalid Password'});
}
} else {
response.push({'result' : 'error', 'msg' : 'User Not Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
} else {
response.push({'result' : 'error', 'msg' : 'Please fill required details authenticate'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
};
任何人都可以帮助我吗? 谢谢你提前。
PS:在IE 11中也出现相同的错误