zoukankan      html  css  js  c++  java
  • Express请求处理-GET和POST请求参数的获取

    场景

    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

    输入内容点击提交

  • 相关阅读:
    python中创建列表、元组、字符串、字典、集合
    python中字典的键不允许重复
    python中生成字典
    python中实现列表元素的倒序排列
    python中实现字典的逆向排列
    python中增加字典的键值对(项)、修改键值对的值
    python中访问字典
    Fortran 2003:完美还是虚幻?(节选)
    感谢裘宗燕老师!
    “符号化”的效用和缺失
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/13311049.html
Copyright © 2011-2022 走看看