设置 contentType 时 jquery ajax 不工作

标签 jquery ajax node.js express

我有两个 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/jsonjavascript/jsontext/json。让它为:text/htmltext/plain。让我知道它是否有效。

关于设置 contentType 时 jquery ajax 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678180/

相关文章:

javascript - Prestashop 送货时选择隐藏/显示付款方式

javascript - 如何使用 webpack 将两个或多个函数导出到全局上下文?

javascript - RangeSlider 显示多个输出

javascript - 使用 $.parseJson() datatables.js 添加 aocolumns

javascript - 单击按钮更改 UI 布局

node.js - 如何在 Mongoose 中为 REST API 创建虚拟

javascript - 从 firebase 数据库获取数据不起作用

javascript - 表单中的复选框到 javascript 到 php

jquery - 无法在 droppable 上删除 jquery ui helper

javascript - 如何使用jquery监控ajax请求的进度响应