我现在已经阅读了stackoverflow帖子的dussins但是我无法让我的bodyparser工作。为了不使事情变得复杂,我改变了我能想象到的最简单的东西,这是下面的代码,只涉及解析一条路线。任何人都可以看到问题吗?
路由/ login.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.get('/', (req, res) => {
res.send('<form method="POST" action="'+ req.originalUrl +'"><input type="text" id="personalNumber" autocomplete="off"><input type="submit" value="Log in"></form>');
res.end();
});
router.post('/', bodyParser.urlencoded({ extended: false }), (req, res) => {
console.log('personal', req.body, req.personalNumber, res.body, req.headers);
res.send('personal', req.body, req.personalNumber, res.body, JSON.stringify(req.headers));
res.end();
});
module.exports = router;
server.js简化
var express = require('express');
var app = express();
var login = require(__dirname + '/routes/login');
app.use('/login', login);
app.listen(80, () => {
console.log('Listening on port 80');
});
转到/登录,在输入中输入任何内容并提交(触发帖子到/ login)将使用以下控制台输出:
Listening on port 80
personal {} undefined undefined { host: 'localhost',
connection: 'keep-alive',
'content-length': '0',
pragma: 'no-cache',
'cache-control': 'no-cache',
origin: 'http://localhost',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
referer: 'http://localhost/login',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-US,en;q=0.8,sv;q=0.6' }
预期输出将由req.body包含有关表单中数据的一些信息。
req.body = {
personalNumber: 'inputData'
};
答案 0 :(得分:1)
之前添加到主文件中时可正常工作
body-parser
在所有routes
因此,在express
文件
server.js
对象后,请输入以下代码
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
答案 1 :(得分:0)
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.urlencoded({ extended: false });
router.use(bodyParser.json());
router.get('/', (req, res) => {
res.send('<form method="POST" action="'+ req.originalUrl +'"><input type="text" id="username" autocomplete="off"><input type="submit" value="Log in"></form>');
res.end();
});
router.post('/', (req, res) => {
console.log('personal', req.body, req.personalNumber, res.body, req.headers);
res.send('personal', req.body, req.personalNumber, res.body, JSON.stringify(req.headers));
res.end();
});
module.exports = router;
试试这个,它可能有用。