Javascript 如何在NodeJS中从jquery接收post数据

Javascript 如何在NodeJS中从jquery接收post数据,javascript,jquery,node.js,Javascript,Jquery,Node.js,这是我的jQuery代码: $.ajax({ url: 'http://localhost:3000/generatePDF', data: '{"data": "TEST"}', /* It is about the content "TEST" that I would like to receive/get */ type: 'POST', success: function (data) {

这是我的jQuery代码:

$.ajax({
            url: 'http://localhost:3000/generatePDF',
            data: '{"data": "TEST"}', /* It is about the content "TEST" that I would like to receive/get */
            type: 'POST',
            success: function (data) {
                console.log('Success: ');
            },
            error: function (xhr, status, error) {
                console.log('Error: ' + error.message);
            }
        });
这是我在NodeJS服务器中的代码:

app.post("/generatePDF", function (req, res) {
    console.log(req);
    res.sendStatus(200);
    return;
});

我想接收我用jQuery代码发送的帖子数据。我该怎么做?或者我可以用普通Javascript实现吗?

如果您使用的是express,您需要
req.body

app.post("/generatePDF", function (req, res) {
    console.log(req.body);
    res.sendStatus(200);
    return;
});

最简单的方法是使用Express服务器和正文解析器

这样,您的NodeJS服务器就可以沿着线路进行查看

var express = require("express");
var bodyParser = require("body-parser");

var app = express();
var PORT = process.env.PORT || 3001;

app.use(bodyParser.json());

app.post("/generatePDF", function (req, res) {
    console.log(req.body);
    res.json({
      status: 'OK'
    })
});

app.listen(PORT, () => {
  console.log("Server running at http://localhost:" + PORT);
});
curl的结果为

$ curl -X POST "http://localhost:3001/generatePDF" -H "Content-Type: application/json" --data '{"data": "TEST"}'
{"status":"OK"}
NodeJS服务器日志

$ node server.js
Server running at http://localhost:3001
{ data: 'TEST' }
请确保向API发送内容类型:application/json标题和帖子

您可以通过在$.ajax options对象中添加新键,将标题添加到调用中

$.ajax({
    headers: { 'Content-Type': 'application/json' }
});

多亏了克里斯蒂安,我找到了解决办法

我需要实现以下代码:

app.use(bodyParser.urlencoded({ extended: true }));

但是为什么?

您使用的是express吗?我使用的是express,但是您提供的答案不起作用,这是因为jquery发送的post请求的内容类型标题默认值为“application/x-www-form-urlencoded;charset=UTF-8”。bodyParser使.json()和.urlencoded()方法都是单独的,以前它们是在同一个bodyParser()函数后面。如果您想在nodejs服务器中以json的形式处理数据,我强烈建议您在应用程序中使用bodyParser.json(),并按照我的回答中的说明在POST请求中发送内容类型:application/json header。@Riku感谢您解释得很好的回答