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은 항상 비어 있습니다. 나는 그런 행동을 기술 한 다른 사례를 보았지만 관련 답변은 여기에 적용되지 않았다.
도와 주셔서 감사합니다.
요청 본문이 [a multipart' 메시지] (http://en.wikipedia.org/wiki/MIME#Multipart_messages)이고 'body-parser' 모듈이 다음과 같은 데이터 구문 분석을 지원하지 않습니다. 그 형식. [README의 두 번째 단락] (https://www.npmjs.org/package/body-parser#readme)은 사용할 수있는 다른 모듈에 대한 제안을 제공합니다. –
또는 'POST'요청의 데이터에'multipart'가 필요하지 않으면 ['x-www-form-urlencoded']로 보낼 수 있습니다 (http://en.wikipedia.org/wiki/Percent- encoding # The_application.2Fx-www-form-urlencoded_type). 이것은'bodyParser.urlencoded()'가 해석하는 형식입니다. –
사실, 지적 해 주셔서 고맙습니다. 내 HTTP에 대한 지식이 제한되어 있으므로 form-urlencoded에 대해 알지 못했습니다. 그렇게하면, 내 node.js가 작은 각형 프론트 엔드의 게시물 요청을 제대로 처리 할 수 있습니다. 도와 주셔서 감사합니다! – Jem