2014-10-13 1 views
14

Node.js 서버로 전송 된 게시물 요청의 양식 데이터를 복구 할 수 없습니다.Node.js (express & bodyParser 사용) : 게시물 요청에서 양식 데이터를 가져올 수 없습니다.

POST 요청

POST /api/login HTTP/1.1 
Host: localhost:8080 
Cache-Control: no-cache 

----WebKitFormBoundaryE19zNvXGzXaLvS5C 
Content-Disposition: form-data; name="userName" 

jem 
----WebKitFormBoundaryE19zNvXGzXaLvS5C 

NodeJS 서버 코드

var express = require('express');  // call express 
var app  = express();     // define our app using express 
var bodyParser = require('body-parser'); 

app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json()); 
app.use(bodyParser()); 

app.all('/*', function(req, res, next) { 
    res.header('Access-Control-Allow-Origin', '*'); 
    res.header('Access-Control-Allow-Headers', 'Content-Type,accept,access_token,X-Requested-With'); 
    next(); 
}); 

var port = process.env.PORT || 8080;  // set our port 

var router = express.Router();    // get an instance of the express Router 

router.get('/', function(req, res) { 

    res.json({ message: 'I am groot!' }); 
}); 

// Login 
router.route('/login') 

    .post(function(req, res){ 

     console.log('Auth request recieved'); 

     // Get the user name 
     var user = req.body.userName; 

     var aToken = getToken(user); 

     res.json({ 

      'token':'a_token' 
     }); 
    }); 

app.use('/api', router); 

app.listen(port); 

로그인 방법 : 나는 (크롬의 우편 배달부를 사용하여 전송) 서버 코드 및 POST 요청 아래에 넣었습니다 req.body.userName을 얻으려고하지만 req.body은 항상 비어 있습니다. 나는 그런 행동을 기술 한 다른 사례를 보았지만 관련 답변은 여기에 적용되지 않았다.

도와 주셔서 감사합니다.

+3

요청 본문이 [a multipart' 메시지] (http://en.wikipedia.org/wiki/MIME#Multipart_messages)이고 'body-parser' 모듈이 다음과 같은 데이터 구문 분석을 지원하지 않습니다. 그 형식. [README의 두 번째 단락] (https://www.npmjs.org/package/body-parser#readme)은 사용할 수있는 다른 모듈에 대한 제안을 제공합니다. –

+2

또는 'POST'요청의 데이터에'multipart'가 필요하지 않으면 ['x-www-form-urlencoded']로 보낼 수 있습니다 (http://en.wikipedia.org/wiki/Percent- encoding # The_application.2Fx-www-form-urlencoded_type). 이것은'bodyParser.urlencoded()'가 해석하는 형식입니다. –

+0

사실, 지적 해 주셔서 고맙습니다. 내 HTTP에 대한 지식이 제한되어 있으므로 form-urlencoded에 대해 알지 못했습니다. 그렇게하면, 내 node.js가 작은 각형 프론트 엔드의 게시물 요청을 제대로 처리 할 수 ​​있습니다. 도와 주셔서 감사합니다! – Jem

답변

16

일반적으로 표현 패키지는 req.body에 본문이 포함될 수 있도록 적절한 body-parser middleware을 지정해야합니다.

[EDITED]

  1. 당신은 URL 인코딩 (비 다중) 폼 데이터뿐만 아니라 JSON의 구문 분석 필요한 경우 추가 시도 :

    // Put this statement near the top of your module 
    var bodyParser = require('body-parser'); 
    
    
    // Put these statements before you define any routes. 
    app.use(bodyParser.urlencoded()); 
    app.use(bodyParser.json()); 
    

    먼저거야 을 package.jsondependencies 속성에 추가 한 다음 npm update을 수행해야합니다.

  2. 여러 부분으로 구성된 양식 데이터를 처리하려면 bodyParser.urlencoded() 본문 파서가 작동하지 않습니다. 여러 부분 본문을 파싱하려면 suggested modules here을 참조하십시오.

+2

OP는 'body-parser'가 사용되고 있음을 보여줍니다. 그러나 모듈은'multipart' 파싱을 지원하지 않습니다. –

+1

멀티 파트 폼 구문 분석을 위해 제안 된 모듈에 대한 참조를 포함하도록 답변을 편집했습니다. 참조 용 @Jonathan에게 감사드립니다. – cybersam

+0

도움에 감사드립니다. 사실, 서버가 URL로 인코딩 된 데이터를 수락 할 수 있다는 것을 모른 채 폼 데이터를 보냈습니다. 후자와 함께 작동합니다. – Jem

1

파일 업로드를 지원하는 multipart/form-data 요청을 처리하려면 multer 모듈을 사용해야합니다. npm link for multer middleware

+0

multer가 업로드를 처리하기 전에 게시판에서 본문을 읽는 방법은 무엇입니까? –

관련 문제