javascript - req.body 未定义-nodejs

标签 javascript 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),但这也是未定义的。

提前致谢!

最佳答案

您缺少将 req.body 设置为值所必需的 body-parser 中间件。 Express 默认情况下不附带此功能,需要通过 NPM npm i --save body-parser

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

关于javascript - req.body 未定义-nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443321/

相关文章:

node.js - 我打算如何在 swaggerize-express 中使用处理程序和数据提供程序?

node.js - Jade 中的 Json 解析

javascript - 根据其他选择使用 Javascript 更改 Select 标签

javascript - 符号>>在javascript中意味着什么

javascript - ASP.Net MVC jQuery UI DatePicker 日期格式

javascript - 创建回历日期选择器

javascript - NodeJS 和类限制

javascript - 如何访问meteor.js中集合的元素?

javascript - 是否可以使用快速路线正则表达式中的捕获组?

node.js - psql 查询没有返回正确的结果?