Express服务器无法读取POST表单的req.body参数报错如何解决
问题原因
Express 4.x及以上版本不再内置请求体解析中间件,你没有手动配置对应解析规则的情况下,req.body默认是undefined,读取其下的属性自然会触发类型错误。
解决步骤
- 在创建Express实例后、定义路由前,添加表单请求体解析中间件:
ourApp.use(express.urlencoded({ extended: false }))
该中间件会自动解析Content-Type: application/x-www-form-urlencoded格式的请求体,也就是普通form表单提交的内容,解析完成后会挂载到req.body上。
如果后续你需要处理JSON格式的POST请求,可以额外添加JSON解析中间件:
ourApp.use(express.json())
- 修改后的完整代码如下:
let express = require("express") let ourApp = express() // 新增:解析表单提交的请求体 ourApp.use(express.urlencoded({ extended: false })) ourApp.get("/", function(req, res) { res.send(` <form action='/answer' method='POST'> <p>What color is the sky on a clear and sunny day?</p> <input name="skyColor" autocomplete="off"> <button>Submit Answer</button> </form> `) }) ourApp.post('/answer', function(req, res) { // 可选优化:转大写后比较,不限制用户输入大小写 if(req.body.skyColor.toUpperCase() == "BLUE") { res.send(` <p>Congrats! You got the right answer.</p> <a href="/">Back to homepage</a> `) } else { res.send(` <p>Sorry, you got the wrong answer. Please try again</p> <a href="/">Back to homepage</a> `) } }) ourApp.get('/answer', function(req, res) { res.send("Are you lost? There is nothing to see here.") }) ourApp.listen(3000)
额外优化提示
- 原有代码中错误提示里的
wrond为拼写错误,已修正为wrong - 新增的
toUpperCase()逻辑可以兼容用户输入小写、混合大小写的正确答案,提升体验
内容的提问来源于stack exchange,提问作者Maxwell200073
相关产品推荐
相关产品推荐

