body-parser读取json post data node.js express

时间:2016-03-04 16:06:37

标签: json node.js express content-type body-parser

我正在使用"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.bodyundefined,我做了一些搜索,发现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];

2 个答案:

答案 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)

好的,找到问题...但我无法解释为什么会发生这种情况.. 要开始阅读json体,我必须改变方法:

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

这个:

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

所有事情都开始起作用了