在node express中请求body undefined

时间:2016-05-05 07:07:51

标签: node.js post express request

在node express中,当我尝试从表单中访问post值时,它显示请求体未​​定义错误。 这是我的代码,

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');
});

请任何人帮我查一下请求正文显示未定义的原因。

2 个答案:

答案 0 :(得分:1)

首先启用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))
})

答案 1 :(得分:0)

如果您没有将express用于网络服务器而只使用普通的http。使用body模块。

相关问题