我有两个 Node js 服务器在 localhost:3000 和 localhost:3001 上运行。当我从 localhost:3001 向 localhost:3000 发出 ajax POST 请求时,没有任何反应。我检查了 localhost:3000 上的日志,它甚至没有收到 POST 请求。
这是我进行 ajax 调用的代码:
$.ajax({
type:"POST",
url:"http://localhost:3000/post/",
contentType:"application/json",
dataType:'json',
data: JSON.stringify({name:'Bruce Wayne'}),
success:function(response) {
console.log(response);
}
});
但是,当我删除 contentType 字段或将其更改为“text/plain”而不是“application/json”时,它会起作用。在 localhost:3000 上,我也在响应中发送这些 header 。
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
我已经解决了很多关于SO的问题并尝试了一切。有人可以帮我找出问题所在吗?谢谢。
最佳答案
这是 jQuery 的一个长期存在的问题,就个人而言,不要问我为什么,但有效的解决方案是:
$.ajax({
type: "POST",
url: "http://localhost:3000/post/",
// contentType: "application/json", // Remove this bit.
// dataType: 'json', // Remove this bit.
data: JSON.stringify({name:'Bruce Wayne'}),
success:function(response) {
console.log(response);
}
});
在发送响应 header 时,请勿提供 application/json
或 javascript/json
或 text/json
。让它为:text/html
或text/plain
。让我知道它是否有效。
关于设置 contentType 时 jquery ajax 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678180/