我正在使用 "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
的定义需要位于 routes
定义之前。 post
请求需要具有 "Content-Type": "application/json"
。
我有这个,但仍然得到未定义
....
如果我使用 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 - body-parser读取json post数据node.js express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800631/