我使用"body-parser": "1.15.0"
和"express": "4.13.4"
而我试图从http
POST请求的body
部分得到json
数据。身体解析器读取JSON数据后node.js的表达
这是我的代码:
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
需求的定义是routes
定义之前。 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];
你是如何发送JSON服务器? –
嗨,我从ios应用发送帖子,并使用先进的REST客户端(铬插件)来测试,但得到相同的结果...我测试头正在发送,他们有正确的内容类型 – Jordan
看到我的答案和尝试它,我已经回答假设你的客户端将发送纯'json',如果是这样它应该工作 –