【发布时间】:2018-11-02 22:10:24
【问题描述】:
我知道已经有人问过类似的问题,但我找不到任何适合我的东西。
我正在尝试将一些 HTML 表单数据发布到我的 app.js 文件中。
这是我的 index.handlebars 文件:
<form method = 'post' action = '/refund'>
<input type = "text" name = "transId" placeholder = "transID">
<input type = "text" name = "amount" placeholder = "amount">
<input type = "submit">
此帖子到以下路线:
//refund route
app.post('/refund', (req, res, next) => {
console.log(req.body.amount);
console.log(req.body.transId);
但是,我收到错误消息:TypeError: Cannot read property 'amount' of undefined
我尝试了各种组合,只是通过req.body,req.params,一切都只是undefined。
【问题讨论】:
-
你有bodyparser吗? -> expressjs.com/en/4x/api.html#req.body
-
我尝试过以下方法:const bodyParse = require('body-parser');常量 formParse = bodyParse.raw(); app.post('/refund', formParse, (req, res, next) => { console.log(req.body.amount); 还是不行
-
你试过
app.use(bodyParser.urlencoded({ extended: false }));作为中间件吗?由于您是从<form>发送数据。还有一件事,尝试提供完整的 URL,例如//myapp.herokuapp.com/refund到action属性的<form> -
@VladimirJovanović,成功了,谢谢!
-
好的,我会发布答案
标签: html node.js express handlebars.js