我正在使用"body-parser": "1.15.0"
和"express": "4.13.4"
我正在尝试从json
帖子请求的body
部分获取http
数据。
这是我的代码:
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];
答案 0 :(得分:0)
尝试在代码中替换以下行:
app.use(bodyParser.json());
以下:
def QuestionnaireTitle(self):
Title = Label(self, text='Questionnaire', bg='firebrick', fg='white', width=50, font=('MS', 24, 'bold'))
Title.grid(row=0,column=0, columnspan=4, rowspan=1)
def QuestionnaireQuestions(self):
db = connect("openDay.db")
allQuestions = []
questionsDict = dict()
#Questions
for i in range(13):
j = get_questionniare_question(db,i)[0]
allQuestions.append(j)
for a in range(len(allQuestions)):
questionsDict["Q"+str(i)] = allQuestions[i]
for key,value in questionsDict.items():
i+=1
key = Label( text=value, font=('Helvetica', 12, 'bold'))
key.grid(row=i, sticky=W)
答案 1 :(得分:0)
app.use(function(req,res,next)
这个:
app.use('/',bodyParser.json(),function(req,res,next)
所有事情都开始起作用了