req.body未定义 - nodejs

时间:2017-04-16 23:40:16

标签: node.js express request

这是我的HTML:

<form action='/new'  method='POST' >
  <span>pool name: </span>
  <input type="text" name="name" />
  <input type="hidden" name="imageSrcList" />
  <button type='submit' >Create new</button>
</form>

这是相关的JS:

var app = express()
app.use(fileUpload());
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/views'));
app.post('/new', (req, res) => {
    console.log(req.body.name);
  })

控制台读出:

TypeError: Cannot read property 'name' of undefined

我尝试使用console.log(req.body),这也是未定义的。

提前致谢!

1 个答案:

答案 0 :(得分:7)

您错过了将body-parser设置为值所必需的req.body中间件。默认情况下,Express不提供此功能,需要通过NPM安装npm i --save body-parser

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))