node.js - Node.js 表示 :can not get the data posted by jquery ajax

标签 node.js post express

在客户端,我使用jquery来发布数据:

        var data = {
            'city': 'england'
        }
        $.ajax({
            'type': 'post',
            'url': 'http://127.0.0.1:8000/',
            'data': data,
            'dataType': 'json',
            'success': function () {
                console.log('success');
            }
        })

在我的 server.js 中,我 try catch 发布数据:

var express = require('express');
var app = express.createServer();
app.configure(function () {
    app.use(express.static(__dirname + '/static'));
    app.use(express.bodyParser());
})

app.get('/', function(req, res){
    res.send('Hello World');
});

app.post('/', function(req, res){
    console.log(req.body);
    res.send(req.body);
});
app.listen(8000);

帖子可能成功,它返回 200 状态,但我无法记录帖子数据,它什么也不返回,并且终端日志未定义

为什么?我该如何解决这个问题?

最佳答案

您发送的数据不正确。

$.ajax({
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json',
  url: '/endpoint'
});

对于 jQuery,使用

contentType:'application/json'

发送 JSON 数据。

关于node.js - Node.js 表示 :can not get the data posted by jquery ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11671405/

相关文章:

javascript - 无法获取配置 json 文件

javascript - 翻转操作数时,将空数组与空对象相加会产生不同的结果

javascript - 如何将此 AJAX 请求函数(原始 Javascript)转换为使用 POST 而不是 GET?

RCurl表单登录

express - 如何使用 SSL 但从 LAN 上的另一台计算机访问自签名网络服务器?

javascript - 在node.js中运行示例代码成功,但在浏览器中运行修改后的代码失败

node.js - Nodejs Swagger 无法向请求添加授权 header

forms - 在不填写表格的情况下在 Selenium 中发出 POST 请求?

node.js - ExpressJS 删除连接

reactjs - 服务器的 socket.io 监听器无缘无故地触发两次