【问题标题】:Node.js POST API and parsing of request bodyNode.js POST API 和请求正文的解析
【发布时间】:2016-08-10 19:15:32
【问题描述】:

作为一个 Node 新手,我似乎在一些非常基本的步骤上苦苦挣扎。有人能指出我正确的方向吗?

本质上,我正在尝试将输入从 iOS(Objective-C)客户端发送到 Node.js 服务器,但不知何故无法解析 http 消息体。事实上,如果我在服务器上的 POST API 中记录相同的数据,则从客户端发布的数据甚至不会出现在请求中。我可以确认端点是正确的,因为正在打印其他日志......这是我的 iOS 和 Node 代码 - 似乎非常简单......

感谢您的意见...

iOS 代码:

- (IBAction)sendUsername:(id)sender
{
    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://MYURL:PORT/registerUser"]];

    NSDictionary *sentData = [[NSDictionary alloc] initWithObjectsAndKeys:@"socool", @"username", nil];
    NSError *theError = nil;
    NSData *postData = [NSJSONSerialization dataWithJSONObject:sentData options:NSJSONWritingPrettyPrinted error:&theError];

    [postRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [postRequest setHTTPMethod:@"POST"];
    [postRequest setHTTPBody:postData];

    // Have tried with both - initWithRequest and with sendSyncRequest - both dont show the req.body on the server...

    // NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];

    NSError *returnedError = nil;
    NSURLResponse *urlResponse = [[NSURLResponse alloc] init];
    NSData *dataResponse = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&urlResponse error:&returnedError];  
}

Node.js 代码:

app.post('/registerUser', function(req, res) {
    console.log("Request to register new user received"); // This gets printed successfully...    

    body = [];
    body = Buffer.concat(body).toString();           

    console.log("Targeted output is: ", req.body.username); // req.body itself keeps coming as undefined.
}); 

【问题讨论】:

    标签: javascript ios objective-c node.js rest


    【解决方案1】:

    看起来您正在使用 ExpressJS。如果是这种情况,在使用 app.post 设置路由之前,您是否指定了 bodyParser?

    看看这个:http://expressjs.com/en/api.html

    特别是“req.body”部分。

    Express 依赖于一个中间件,该中间件将拦截请求、解析它,然后用它填充 req.body。

    【讨论】:

    • 呃……当一个人在不理解的情况下不复制代码时会发生什么!谢谢@Chazzu
    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2020-08-20
    相关资源
    最近更新 更多