app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
next();
});
和客户端应用http://localhost:8080,并希望将数据发布到服务器。 我使用XMLHttpRequest:
execute(url, requestType, params) {
return new Promise(
(resolve, reject) => {
var request = new XMLHttpRequest();
request.open(requestType, url, true);
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('Content-Type', 'application/json');
request.onload = () => {
switch (request.status) {
case 201:
case 200:
resolve(request.response);
break;
default:
reject(`${Constants.ERRORS.NETWORK}: ${request.statusText}`);
break;
}
}
request.onerror = () => {
reject(Constants.ERRORS.NETWORK);
};
params ? request.send(params) : request.send();
});
};
当我使用execuete("http://localhost:3000/register", "POST", {"some": "data"})
时,我有错误请求头字段Access-Control-Allow-Origin在预检响应中不允许使用Access-Control-Allow-Origin。
我该如何解决?
答案 0 :(得分:1)
之前我遇到过类似问题,并使用
修复app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
或
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
答案 1 :(得分:0)
application/json
是Content-type
请求标头的非简单值(请参阅my answer on How does Access-Control-Allow-Origin header work?中“非简单请求”的开头,因此必须由服务器明确允许通过响应标题Access-Control-Allow-Headers: application/json
。只需添加行
res.header("Access-Control-Allow-Headers", "application/json");
到您的服务器代码。