【问题标题】:$.ajax post doesn't post data (JavaScript)$.ajax post 不发布数据 (JavaScript)
【发布时间】:2017-09-29 05:54:48
【问题描述】:

我无法弄清楚为什么会出现这个问题。当我在我的 javascript 文件中发出 ajax 发布请求时,会调用 url,但不会发送数据。以下是我发出帖子请求的方式:

<script type="text/javascript">
    $.ajax({
        type: "POST",
        url: "/test",
        dataType: "json",
        data: {test: "test"},
        contentType: "application/x-www-form-urlencoded",

    });
</script>

在我的后端,这是我正在使用的 post 方法:

app.post('/test', function(req, res) {
  console.log(req.body); // returns {}
  console.log(req.params); // returns {}
});

这是我迄今为止尝试过的:XMLHttpRequest to Post HTML FormAJAX Post not sending form dataSend POST data using XMLHttpRequest,但不幸的是,它们都不适合我。

【问题讨论】:

  • 您可以删除 contentType 选项,这对于您正在做的事情不是必需的。 (默认就足够了)
  • 您确定要达到终点?每当您发送 AJAX 请求时,您都会在服务器端的控制台中看到一些东西?您是否尝试过 console.log(req) 来查看数据是否在不同的属性上?
  • 试试JSON.stringify({test: "test"})
  • @KevinB 我也试过没有 contentType,但还是不行。还有其他建议吗?
  • 您必须向 FE 发送一些回复,对吗? res.send('something') ??否则该请求将在浏览器中超时

标签: javascript jquery node.js ajax post


【解决方案1】:

dataType: "json" 需要 JSON 格式的数据,但 contentType: "application/x-www-form-urlencoded" 以不同的方式发送数据。也许你应该写dataType: "json", contentType: "application/json"dataType: "html", contentType: "application/x-www-form-urlencoded"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2018-02-01
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多