2016-08-10 3 views
0

이 노드 초보자 인 경우 몇 가지 매우 기본적인 단계로 어려움을 겪고있는 것 같습니다. 누군가가 나를 올바른 방향으로 향하게 할 수 있습니까?Node.js POST API 및 요청 본문의 파싱

본질적으로 iOS (Objective-C) 클라이언트에서 Node.js 서버로 입력을 보내려고하지만 http 메시지 본문을 구문 분석 할 수 없습니다. 사실 서버에서 POST API에 동일한 정보를 기록하면 클라이언트에서 게시되는 데이터가 요청에 나타나지 않습니다.

:

아이폰 OS 코드 ...

이 입력을 감사합니다 ... 매우 간단 것 같다 - 나는 엔드 포인트가 다른 로그 인쇄하기 때문에 정확한지 확인할 수 있습니다 ... 여기 내 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를 코드는 : 당신이 ExpressJS을 사용하고 같은

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

것 같습니다. 그렇다면 app.post를 사용하여 경로를 설정하기 전에 bodyParser를 지정 했습니까?

이것 좀 봐 : http://expressjs.com/en/api.html

특히, 'req.body'섹션을.

Express는 요청을 가로 채서 구문 분석 한 다음 req.body를 채울 미들웨어에 의존합니다.

+0

음 ... 이해하지 않고 코드를 복사하지 않으면 어떻게 될까요? 고마워요 @ Chazzu – vikram17000