Express:POST参数的获取
Express中接收POST请求参数,需要用到一个第三方模块:body-parser。 如果要使用该模块,需要在命令行工具中使用npm install body-parser安装第三方模块。
操作代码示例:
// 引入express框架 const express = require(express); // 引入body-parser模块 const bodyparser = require(body-parser); // 创建网站服务器 const app = express(); // 拦截所有请求 urlencoded()里的参数是必填的 // extended:false表示方法内部使用querystring模块处理请求参数的格式 // extended:true表示方法内部使用第三方模块qs处理请求参数的格式 // 默认使用extended:false即可满足我们的需求 app.use(bodyparser.urlencoded({extended:false})) // 处理POST请求参数 app.post(/add,(req,res) => { // body属性就是bodyparser在req中添加的属性,属性的值就是post请求参数,直接响应给客户端 res.send(req.body); }) // 监听端口 app.listen(3000); console.log(网站服务器启动成功);
因为是POST请求参数,因此还需要一个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>Document</title> </head> <body> <form action="http://localhost:3000/add" method="POST"> <input type="text" name="uname" id="">用户名 <input type="password" name="password" id="">密码 <input type="submit" value="提交"> </form> </body> </html>
最后执行结果如下: 点击提交后: