【问题标题】:Not able to take inputs from HTML form with Node Js无法使用 Node Js 从 HTML 表单中获取输入
【发布时间】:2021-01-16 13:59:20
【问题描述】:

我正在尝试从我的 js 文件中的 html 表单接收输入。

HTML

<form action='/bmicalc' method="post">
      <input type='text' name='h' placeholder='Height'>
      <input type='text' name='w' placeholder='Weight'>
      <button type='submit' name='sub'>Calculate</button>
</form>

JS

const express=require('express');
const app=express();

app.get('/',function(req,res){
  res.send('<h1>Hello There!<h1>');
});

app.get('/bmicalc',function(req,res){
  res.sendFile(__dirname+'/bmicalc.html');
})

app.post('/bmicalc',function(req,res){
  console.log(req.body.h);
});

app.listen(3000,function(){
  console.log("Started server on port 3000");
})

但是我总是收到以下错误:

TypeError: 无法读取未定义的属性“h”

有人可以帮忙指出错误吗?

【问题讨论】:

  • 看来req.bodyundefined。所以这就是为什么你不能访问属性h
  • 但我在 html 正文标签中有表单标签。那么为什么要显示未定义呢?

标签: javascript html node.js backend


【解决方案1】:

Express API reference 明确了以下声明(强调我的):

req.body

​​>

包含在请求正文中提交的数据键值对。 默认为undefined,使用时填充 正文解析中间件,例如 express.json()express.urlencoded().

您发布的代码示例没有使用文档引用的中间件。您可以利用app.use() 来启用它们:

const express=require('express');
const app=express();

app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.get('/',function(req,res){
  res.send('<h1>Hello There!<h1>');
});

app.get('/bmicalc',function(req,res){
  res.sendFile(__dirname+'/bmicalc.html');
})

app.post('/bmicalc',function(req,res){
  console.log(req.body.h);
});

app.listen(3000,function(){
  console.log("Started server on port 3000");
})

【讨论】:

猜你喜欢
  • 2021-03-08
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
相关资源
最近更新 更多