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

分手后的思念是犯贱 2023-10-06 13:03 139阅读 0赞

场景

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

Node的Web应用框架Express的简介与搭建HelloWorld_霸道流氓气质的博客-CSDN博客

注:

博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

GET请求的参数的获取

通过res.query获取

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

完整示例代码

  1. //引入express框架
  2. const express = require('express');
  3. //创建网站服务器
  4. const app = express();
  5. app.get('/',(req,res)=>{
  6. res.send(req.query);
  7. })
  8. app.listen(3000, function () {
  9. console.log('Example app listening on port 3000!')
  10. })

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

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70

POST请求参数的获取

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

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

  1. npm install body-parser

或者

  1. cnpm install body-parser

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 1

然后在app.js中引入

  1. const bodyParser = require('body-parser');

然后在创建路由时

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

完整示例代码

  1. //引入express框架
  2. const express = require('express');
  3. const bodyParser = require('body-parser');
  4. //创建网站服务器
  5. const app = express();
  6. //拦截所有请求
  7. //extended:false 方法内部使用querystring模块处理请求参数的格式
  8. //extended:true 方法内部使用第三方模块qs处理请求参数的格式
  9. app.use(bodyParser.urlencoded({extended:false}))
  10. app.post('/add',(req,res)=>{
  11. //接收post请求参数
  12. res.send(req.body);
  13. })
  14. app.listen(3000, function () {
  15. console.log('Example app listening on port 3000!')
  16. })

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Document</title>
  5. </head>
  6. <body>
  7. <form action = "http://localhost:3000/add" method="POST">
  8. <input type="text" name = "key">
  9. <input type="text" name = "value">
  10. <button type="submit">提交</button>
  11. </form>
  12. </body>
  13. </html>

在浏览器中打开post.html
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 2

输入内容点击提交

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 3

发表评论

表情:
评论列表 (有 0 条评论,139人围观)

还没有评论,来说两句吧...

相关阅读

    相关 GET 请求 POST 请求

    GET 请求和 POST 请求: 1). 使用GET方式传递参数: ①. 在浏览器地址栏中输入某个URL地址或单击网页上的一个超链接时,浏览器发出的HTTP请求消