Node.js(使用express&bodyParser):无法从post请求中获取表单数据
我似乎无法恢复发送到我的Node.js服务器的发布请求的表单数据。 我已经把服务器代码和post请求(使用postman in chrome发送)放在下面:
发布请求
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);
login方法试图获得req.body.userName – 然而,req.body总是空的。 我已经看到其他案例描述这样的行为,但没有相关的答案在这里适用。
感谢您的帮助。
通常,快速应用程序需要指定适当的body-parser中间件 ,以便req.body
包含正文。
[EDITED]
-
如果您需要parsingurl编码(非多部分)表单数据以及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());
首先,您需要将body-parser添加到
package.json
的dependencies
属性中,然后执行npm update
。 -
要处理多部分表单数据,
bodyParser.urlencoded()
正文parsing器将不起作用。 请参阅这里build议的模块来parsing多部分主体。
要处理支持file upload的多部分/表单数据请求,您需要使用multer模块。 npm链接为multer中间件