为什么下面的post没问题,但是put请求会报错:
XMLHttpRequest cannot load http://localhost:8001/service. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access.
客户端
$.ajax({
url: 'http://localhost:8001/man',
method: 'POST',
success: function (data) {
console.log(data)
}
});
$.ajax({
url: 'http://localhost:8001/service',
method: 'PUT',
success: function (data) {
console.log(data)
}
});
服务端
app.post('/man', function (req, res) {
var body = req.body;
console.log(body);
if (body) {
res.header("Content-Type", "application/json; charset=utf-8");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
res.send(body);
}
});
app.put('/service', function (req, res) {
res.header("Content-Type", "application/json; charset=utf-8");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
res.send(req.body);
});
问题在于
预请求
,在发起
PUT
请求之前会先发起一次
OPTIONS
请求,报错是针对
OPTIONS
这次请求,请求没有检查到
headers
中设置的
Access-Control-Allow-Origin
。
解决办法:
添加一个对于
OPTIONS
请求的处理
app.options('/service', function (req, res) {
res.header("Content-Type", "application/json; charset=utf-8");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
});
因为
put
不是简单请求,有关跨域,可以看看这个
我没记错的话, 在chrome下面
Access-Control-Allow-Origin
设置成
*
是不行的, 你必须显式的设置成会去调用http地址
你上面的场景应该是设置成
Access-Control-Allow-Origin: http://localhost:63343
如果你确实希望在chrome下面使用
*
要不试试 https://chrome.google.com/web… (我没有尝试过)