javascript - 从 Node 中的请求中提取 JSON 数据

标签 javascript json node.js

为了更熟悉 node.js,我创建了一个带有 Node 服务器的新网站,我正在向服务器发布数据,但我不知道如何读取请求中的 JSON 数据:

客户请求:

 function addSymptom(name) {

        $.ajax({
            type: 'POST',
            url: '/addSymptom',
            data: {
                symName: name
            },
            success: function (data) {
                listSymptoms();
            },
            contentType: "application/json",
            dataType: 'json'
        });

    }

服务器处理程序:

     app.post('/addSymptom', function (req, res) {

        var newSymptom = req.body;
        console.log(newSymptom); // undefined :(

        res.send(JSON.stringify({
            result: 'success'
        }));
     });

为什么 request.body 未定义?我应该以其他方式读取请求正文中的“symName”字段吗?

最佳答案

一定要在 node.js 上添加 bodyParser 模块..

如果您使用的是 Express 3.x/4.x,您只需确保包含 bodyParser:

  1. Express 3.x

    app.use(express.bodyParser({limit : '50mb'}));
    
  2. Express 4.x

在你的包文件中:

"body-parser": "~1.0.0",

或者运行 npm-install body-parser

然后在您的 node.js 服务器中:

var bodyParser = require('body-parser');

// create our app
var app = express();

// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());

示例链接: http://code.runnable.com/U0sU598vXio2uD-1/example-reading-form-input-with-express-4-0-and-body-parser-for-node-js 3.没有 express

如果出于某种原因您决定不使用 express,您可能需要绑定(bind)到套接字的数据处理程序以读取数据。

这是一篇关于此事的文章: http://blog.frankgrimm.net/2010/11/howto-access-http-message-body-post-data-in-node-js/

关于javascript - 从 Node 中的请求中提取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30977395/

相关文章:

javascript - 搜索词条,将其包装到 <span> 标签中

javascript - HTML 5 地理定位在中国

c# - DataContractJsonSerializer 更改我的日期

node.js - npm install everything 失败并显示 ECONNRESET

javascript - 仅使用一个函数 Rand100() 的 1-20 随机数组

.net - JSON 反序列化为继承的类型

java - 从 Postman 发送的带有 JSON 负载的 PUT 请求,未解析嵌套对象

javascript - Node.js Express haml 无法正确呈现

javascript - 将参数从 Controller 传递到 angularjs 中的资源工厂以在数据库中搜索

javascript - 选定的 HTML DIV 元素可拖动使用 JQueryUi draggable