首页 > 解决方案 > 在 express.js 中处理 post 请求

问题描述

我想使用 Node.js 中的 a 表单中给出的值。

这是示例:

index.html : 
    <!DOCTYPE html>
<html lang="en"> 


<head>

</head>

<body>
    <div align="middle"  >
        <!--Ethernet 1 Tab -->
        <form method="POST" action="firstName">
        <p align="left">first name  </br> <input align="middle" name="firstName" placeholder="firstname" id="firstname" ></p> 

        <p align="left"> second name </br>   <input align="middle"   name="secondname" placeholder="second name" ></p>  
      </form>
        <input type="submit" value="Submit" class="button" >

        </div>
</body>
</html>

应用程序.js

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


app.use(express.urlencoded())
console.log(__dirname)

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'))

})
app.post('/firstName', (req, res) => {
  const firstName = req.body.firstName
  console.log(firstName)
})
app.listen(3002);

好吧,我希望在控制台上看到任何东西,但什么也没有。我是 Node.js 的新手。我不明白我所缺少的。

标签: javascripthtmlnode.jsexpress

解决方案


在 Express 4.16+ 版本中,默认情况下会提供正文解析器,因此只需input type="submit"在表单标签内移动即可。

否则你需要 body-parser 包

可以通过正文解析器访问帖子值,因此您需要在代码中包含正文解析器包,然后可以从req.body.firstName

正文解析器初始化

添加这个

var bodyParser = require('body-parser')

const app  = express()

然后在app.use()添加之前

app.use(bodyParser.urlencoded({extended: true}))

编辑:还可以input type="submit"在表单标签内移动您的工作。


推荐阅读