2016-08-10 151 views
0

是一個Node新手,我似乎正在努力與一些非常基本的步驟。請有人指點我正確的方向嗎?Node.js POST API和請求體的解析

本質上,我試圖從iOS(Objective-C)客戶端發送輸入到Node.js服務器,但不知何故無法解析http消息正文。實際上,如果我在服務器上的POST API中記錄相同的數據,則從客戶端發佈的數據甚至不會出現在請求中。我可以確認的端點是正確的,因爲越來越打印其他日誌......這是我的iOS和節點代碼 - 似乎是相當簡單的......

感謝您的投入...

的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. 
}); 

回答

2

它看起來像你使用ExpressJS。如果是這樣,在設置app.post的路線之前,您是否指定了bodyParser?

看看這個:http://expressjs.com/en/api.html

具體地, 'req.body' 部分。

Express依賴於將要攔截請求的中間件,解析它,然後用它填充req.body。

+0

呃......當沒有理解的情況下不復制代碼時會發生什麼?謝謝@Chazzu – vikram17000