我正在将我的项目从 jQuery 迁移到 axios。它在其他地方工作正常,但我在一个特定地方遇到错误。 axios 给出 CORS 错误,但 jquery 工作正常。这是代码:
jQuery
$.ajax({
url: 'my-url-here',
type: 'post',
data: JSON.stringify({
"attachmentNames": [ "filename.pdf" ]
}),
success: function (data) {
console.info(data);
}
});
axios
axios({
url: 'my-url-here',
method: 'post',
data: {
"attachmentNames": [ "filename.pdf" ]
}
}).then(function(resp) {
console.log(resp);
});
最佳答案
浏览器将发送 preflight request如果您发送的 Content-Type
的值不在很短的列表中。
application/json
将触发预检。
默认情况下,Axios 会将数据编码为 JSON,并表示它正在发送 JSON。
在 jQuery 中,您手动将数据编码为 JSON,并且无法设置正确的 Content-Type header 。因此,您对服务器撒谎并声称数据是 application/x-www-form-urlencoded
(jQuery 的默认值)。此 header 不需要预检请求。
配置服务器以响应预检请求,并授予更改Content-Type
的权限(在Access-Control-Allow-Headers
中)。
关于javascript - jQuery ajax 工作但 axios 给出 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60651033/