代码如下:
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: '张三',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
}).then(function(data) {
return data.text()
}).then(function(data) {
console.log(data)
})
出现报错 Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
错误很明显是一个跨域的错误,但是怎么解决呢?
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=wang&pwd=1314520',
headers: {
'Content-Type': 'application/X-WWW-form-urlencoded'
}
}).then(function(data) {
return data.text()
}).then(function(data) {
console.log(data)
})
使用上面的代码就不会报错,区别就在他们的 Content-Type 上面,在网上找了篇文章https://segmentfault.com/a/1190000009971254讲的比较详细,修改了后台代码后就没有报错了
后台代码使用 nodejs,在index中加入了
// 设置允许跨域访问该服务
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); //允许来自所有域名的请求
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); //请求允许的方法
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
设置了上面的跨域操作后就可以运行代码了。