在 Node Express 中,当我尝试从表单访问发布值时,它显示请求正文未定义错误。 这是我的代码,
http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );
}).listen(9000, function() {
console.log('http://localhost:9000');
});
请任何人帮我找出为什么请求正文显示未定义。
最佳答案
启用body-parser首先是中间件
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
关于node.js - 请求正文在 Node Express 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044556/