【问题标题】:Body is undefined when parsing JSON in Express.js在 Express.js 中解析 JSON 时,正文未定义
【发布时间】:2014-03-20 08:56:30
【问题描述】:

我有一个简单的服务器,我只是在它发布时将 json 打印到屏幕上。这是我的代码:

/*jslint node:true*/

var express = require('express');
var app = express();
app.use(express.json());
app.use(app.router);

app.post('/event', function (res, req) {
    //'use strict';
    console.log(req.body);
});

app.listen(3000);

然后我用 curl 将 JSON 放到服务器上:

curl -X POST -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/event

但是服务器只打印undefined

我做错了什么?

【问题讨论】:

  • 添加 app.use(express.bodyParser());紧接在 app.use(app.router); 之后

标签: json node.js express


【解决方案1】:

您尚未定义 express.bodyParser()

必须这样做:

app.use(express.bodyParser());

实时示例: 模块路由文件

exports.post = function(req, res){
    console.log(req.body);
    //res.render('index', { title: 'Express' });
};

应用:

app.post('/post', routes.post);

提琴手请求:

来自 cmets:如果您有最新的库,您应该考虑到 Connect 3.0 已弃用 bodyParser。适当的线程:How to get rid of Connect 3.0 deprecation alert?

【讨论】:

【解决方案2】:

我只是想出了问题所在。应该是:

function (req, res)

而不是:

function (res, req)

因为第一个参数是请求,第二个是响应。

【讨论】:

  • 你甚至没有在你的问题中包含那部分!
猜你喜欢
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多