首页 > 其他 > 详细

Express请求处理-GET和POST请求参数的获取

时间:2020-07-16 00:34:41      阅读:96      评论:0      收藏:0      [点我收藏+]

场景

Node的Web应用框架Express的简介与搭建HelloWorld:

https://mp.csdn.net/console/editor/html/106650798

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

GET请求的参数的获取

通过res.query获取

app.get(/,(req,res)=>{
    res.send(req.query);
})

完整示例代码

//引入express框架
const express = require(express);

//创建网站服务器
const app = express();
app.get(/,(req,res)=>{
    res.send(req.query);
})

app.listen(3000, function () {
  console.log(Example app listening on port 3000!)
})

运行项目,浏览器中输入带参数的请求url

技术分享图片

 

 

技术分享图片

POST请求参数的获取

Express中接受post请求参数需要借助第三方包 body-parser

首先在项目目录下打开终端输入

npm install body-parser

或者

cnpm install body-parser

技术分享图片

技术分享图片

 

 

然后在app.js中引入

const bodyParser = require(body-parser);

然后在创建路由时

//拦截所有请求
//extended:false 方法内部使用querystring模块处理请求参数的格式
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}))
app.post(/add,(req,res)=>{
  //接收post请求参数
  res.send(req.body);
})

完整示例代码

//引入express框架
const express = require(express);
const bodyParser = require(body-parser);
//创建网站服务器
const app = express();


//拦截所有请求
//extended:false 方法内部使用querystring模块处理请求参数的格式
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}))
app.post(/add,(req,res)=>{
  //接收post请求参数
  res.send(req.body);
})


app.listen(3000, function () {
  console.log(Example app listening on port 3000!)
})

为了测试post请求,在项目目录下新建post.html

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <form action = "http://localhost:3000/add" method="POST">
        <input type="text" name = "key"> 
        <input type="text" name = "value"> 
        <button type="submit">提交</button>
    </form>
</body>
</html>

在浏览器中打开post.html

技术分享图片

 

 

技术分享图片

输入内容点击提交

技术分享图片

 

 

技术分享图片

Express请求处理-GET和POST请求参数的获取

原文:https://www.cnblogs.com/badaoliumangqizhi/p/13311049.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!