javascript - 在 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 的新手。我不明白我所缺少的。
解决方案
在 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"
在表单标签内移动您的工作。
推荐阅读
- pysimplegui - 如何滚动到 PySimpleGUI 中的特定表格行
- python - 在python中找到树中所有可能的路径
- c++ - 如何安全地将全局对象复制到指针
- visual-studio-code - VS Code编辑器工作区文件可以指定默认起始目录吗
- objective-c - 在 Objective-C 中,在创建子类时,如何让它知道在超类的 .m 文件中声明的属性?推荐的方法是什么?
- python - 我如何每小时重新采样包含一列推文的数据框?(我想每小时连接所有推文)
- amazon-web-services - 在笔记本启动时安装 jupyterlab 扩展
- excel - 在 Excel VBA 中计算频率
- casting - 将小数(38,10)转换为在pyspark中浮动时截断值
- log4j2 - 使用 log4j2 未生成日志文件