body-parser 读取 json post 数据 node.js 表达

body-parser read json post data node.js express

我正在使用 "body-parser": "1.15.0""express": "4.13.4" 我正在尝试从 http post 请求的 body 部分获取 json 数据。

这是我的代码:

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

var app = express();
///Set Connection config
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

//Body parser
app.use(bodyParser.json(({ type: 'application/*+json', 
                            inflate: false
                        })));

app.use(bodyParser.urlencoded({
  extended: true
}));//Read post info

app.use(function(req, res, next) {

   //Response config
   res.charset = 'utf-8'; 
   res.set({
     'Content-Type': 'application/json'
   });

   console.log("body: " + JSON.stringify(req.body));

});

// Routing
require('./routes')(app,io);//define routes

//Connect
server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

问题是我得到 req.body 作为 undefined,我做了一些搜索,发现 parser 的定义需要在 [= 之前23=]定义。 post 请求需要 "Content-Type" : "application/json".

我有,但仍然得到 undefined.....

如果我使用 app.use(bodyParser.text()); 并更改 "Content-Type" : "plain/text" 它工作正常,使用 "Content-Type" : "x-www-form-urlencoded" 它也可以工作...

但是我需要使用 "Content-Type" : "application/json" 谁能帮帮我?

提前致谢。

编辑:数据从 objective-c

发送
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:60.0];
[request setHTTPMethod:method];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSDictionary* sendInfo = [[NSDictionary alloc]initWithObjectsAndKeys:
                              @"test", @"user" , nil];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonDataString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [jsonDataString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: requestData];

//Capturing server response
NSError* error;
NSHTTPURLResponse* response;
NSData* result = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];

尝试替换代码中的以下行:

app.use(bodyParser.json(({ type: 'application/*+json', 
                            inflate: false
                        })));

以下内容:

app.use(bodyParser.json());

好的,找到问题了……但我无法解释为什么会这样…… 要开始阅读 json 个身体,我必须更改方法:

app.use(函数(req, res, next)

对于这个:

app.use('/', bodyParser.json(), 函数(req, res, next)

一切都开始起作用了