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);
})
报错提示:
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方式传递参数能正常返回,而且二者请求的是相同的接口,但是换成json方式就报上面的错误了
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)
})
上网查了下多数都是说跨域请求问题,试过一遍也没有解决,如果是跨域请求问题,问什么有的报错,有的不报错呢
回答
res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Headers', 'mytoken');
合并到一行
可以试试 https://www.lilnong.top/cors/1010000022879873
这个接口
以上是 fetch post json报错 的全部内容, 来源链接: utcz.com/a/22589.html