使用Express+body-parser获取HTML表单输入报错:Cannot read properties of undefined (reading 'abc')
Express无法获取HTML表单输入,报错TypeError: Cannot read properties of undefined (reading 'abc')
开发项目时,尝试从HTML表单获取输入,多次尝试后仍失败,即使使用了body-parser也无法解决,报错信息为:
TypeError: Cannot read properties of undefined (reading 'abc')
后端代码
const axios = require("axios"); const express=require("express"); const bodyParser=require("body-parser"); const astrology=express(); astrology.use(bodyParser.urlencoded({extended: false})); astrology.use(bodyParser.json()); astrology.get("/",function(_req,res){ res.sendFile(__dirname +"/index.html"); }) astrology.post("/",function(res,req){ const fname = req.body.abc; res.send('<h1>Hello</h1> '+fname') }) astrology.listen(3000,function(){ console.log("server is running at port 3000") })
前端HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>astrology</title> </head> <body> <h1>Astrology</h1> <form action="/" method="post"> <input type="text" id="abc" name="abc"> <input type="submit" name="submit"> </form> </body> </html>
错误原因及修复方案
- POST回调参数顺序错误:Express路由回调的参数顺序是
(req, res)(请求对象在前,响应对象在后),你写反成了(res, req),导致你调用的req实际上是响应对象,自然没有body属性,因此报错。 - 字符串语法错误:
res.send('<h1>Hello</h1> '+fname')中,最后一个引号位置错误,应该去掉fname后面的单引号,或者使用模板字符串更规范。
修正后的后端代码
const axios = require("axios"); const express=require("express"); const bodyParser=require("body-parser"); const astrology=express(); astrology.use(bodyParser.urlencoded({extended: false})); astrology.use(bodyParser.json()); astrology.get("/",function(_req,res){ res.sendFile(__dirname +"/index.html"); }) astrology.post("/",function(req, res){ const fname = req.body.abc; res.send(`<h1>Hello</h1> ${fname}`); }) astrology.listen(3000,function(){ console.log("server is running at port 3000") })
内容的提问来源于stack exchange,提问作者Mayank Tambe
相关产品推荐
相关产品推荐

