zoukankan      html  css  js  c++  java
  • nodejs(14)express获取url中的参数

    问号传参获取参数

    获取 http://127.0.0.1:3001/user?id=10&name=zs 中的查询参数:

    • 直接使用 req.query 获取参数即可;

    • 注意:URL 地址栏中通过 查询字符串 传递的参数,express 框架会直接解析,大家只需使用 req.query 直接获取 URL 中 查询字符串的参数;

    const express = require('express')
    
    const app = express()
    // http://127.0.0.1:3001/user?id=89&name=houfei
    app.get('/user', (req, res) => {
      console.log(req.query)
      res.send(req.query)
    })
    
    app.listen(3001, function() {
      console.log('服务器启动成功了');
    })

    从URL地址中获取路径参数

    从URL地址中获取路径参数:

    • 假设客户端浏览器请求的URL地址为:http://127.0.0.1:3001/user/10/zs

    • 假设后台的路由是 app.get('/user/:id/:name', (req, res) => {})

    • 直接使用 req.params 可以获取URL地址中传递过来的参数;

    const express = require('express')
    
    const app = express()
    // http://127.0.0.1:3001/user/89/houfei
    app.get('/user/:id/:name', (req, res) => {
      console.log(req.params)
      res.send(req.params)
    })
    
    app.listen(3001, function() {
      console.log('服务器启动成功了');
    })

    从post表单中获取提交的数据

    • 借助于body-parser来解析表单数据

    • 安装:npm i body-parser -S

    • 导入:const bodyParser = require('body-parser')

    • 注册中间件:app.use(bodyParser.urlencoded({ extended: false }))

    • 使用解析的数据: req.body 来访问解析出来的数据

    例子:nodejs(7)练习 http 和 express 创建简单的服务器

  • 相关阅读:
    re模块和分组 random模块
    javascript中===和==的区别
    基于jQuery封装一个瀑布流插件
    javascript中天气接口案例
    jQuery中样式和属性模块简单分析
    jQuery中事件模块介绍
    jQueryDOM操作模块(二)
    jQueryDOM操作模块
    jQuery基本选择器模块(二)
    jQuery基本选择器模块
  • 原文地址:https://www.cnblogs.com/houfee/p/10370154.html
Copyright © 2011-2022 走看看