【发布时间】: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