2014-02-19 16 views
2

我有一个简单的服务器,当它发布时,我只是将json打印到屏幕上。这是我的代码:在Express.js中解析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); 

然后,我把一个JSON给服务器的卷曲度:

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

但是服务器只是打印undefined

我到底做错了什么?

+0

Add app.use(express.bodyParser()); app.use(app.router)后立即; –

回答

2

我刚才找出了问题所在。它应该是:

function (req, res) 

而不是:

function (res, req) 

由于第一参数是请求和第二是响应。

+6

你甚至没有在你的问题中包括那部分! – Stephen

5

您还没有定义 express.bodyParser()

它必须这样做用法:

app.use(express.bodyParser()); 

活生生的例子: 模块routes文件

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

应用:

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

提琴手要求:

enter image description here

从意见:如果你有最新的库,你应该考虑到,bodyParser从连接3.0弃用帐户。适当的线程:How to get rid of Connect 3.0 deprecation alert?

+0

我应该做'express.json()'的instaid吗? – Naknut

+0

是的。这一翻译。看看有更多的信息http://stackoverflow.com/questions/10005939/how-to-consume-json-post-data-in-an-express-application –

+2

bodyParser已弃用http://stackoverflow.com/ a/19611997/941764 – jgillich