目录
之前使用x-www-form-urlencoded方式传递参数能正常返回:
fetch--post-- json请求报错
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: 'zhangsan',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
// return data.text();
return response.json();
}).then(function(data) {
console.log(data);
})
1.报错提示:
Access to fetch at 'http://localhost:3000/books/123' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
之前使用x-www-form-urlencoded方式传递参数能正常返回:
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
后台设置:
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');
res.header('Access-Control-Allow-Headers', 'mytoken');
next();
});
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})
2.报错原因:
【fetch不需要设置请求头】
3.解决方法:
【注释掉有mytoken那一行】
// 设置允许跨域访问该服务
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');
// 注释掉有mytoken那一行
// res.header('Access-Control-Allow-Headers', 'mytoken');
next();
});
运行成功: