[英]Cannot access to req.body inside middlewares
我實際上在帶有Express的node.js中有一個非常小的應用程序,我無法訪問req.body。
這是我的app.js
代碼:
var express = require('express'),
middleware = require('./middleware'),
mysql = require('mysql'),
app = express();
app.use(middleware.authenticate);
app.use(middleware.getScope);
app.listen(3000);
module.exports = app;
以及帶有中間件的文件:
var bcrypt = require('bcrypt'),
mysql = require('mysql');
function authenticate(req, res, next){
console.log(req.body);
next();
}
function getScope(req, res, next){
console.log(req.body);
next();
}
module.exports.authenticate = authenticate;
module.exports.getScope = getScope;
在所有情況下,req.body都是undefined
。
我正在發送帶有x-www-form-urlencoded
協議的數據拋出Postman,在這種情況下是必須的。
謝謝!!
你需要添加body-parser
來表達:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
點擊此處查看請求 http://expressjs.com/en/api.html
也許POST路線也可能有所幫助:
app.post('/', function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.