zoukankan      html  css  js  c++  java
  • node.js取参四种方法req.body,req.params,req.param,req.body

    node.js取参四种方法req.body,req.params,req.param,req.body

    1. 参考:https://my.oschina.net/u/2519530/blog/535309
    • 获取请求很中的参数是每个web后台处理的必经之路,nodejs的 express框架 提供了四种方法来实现。

      • 1,req.body

      • 2,req.query

      • 3,req.params

      • 4,req.param()[已被弃用]

    • 首先来介绍第一个 req.body

    官方文档解释:
    Contains key-value pairs of data submitted in the request body. By default, it is undefined,
     and is populated when you use body-parsing middleware such as body-parser and multer.
    
    稍微翻译一下:包含了提交数据的键值对在请求的body中,默认是underfined,
    你可以用body-parser或者multer来解析body
    
    

    解析body不是nodejs默认提供的,你需要载入body-parser中间件才可以使用req.body;此方法通常用来解析POST请求中的数据

    • 第二种是req.query
    官方文档解释:
    An object containing a property for each query string parameter in the route. 
    If there is no query string, it is the empty object, {}.
    翻译一下:包含在路由中每个查询字符串参数属性的对象。如果没有,默认为{}
    

    有nodejs默认提供,无需载入中间件
    此方法多适用于GET请求,解析GET里的参数

    • 第三种是 req.params
    官方文档:
    An object containing properties mapped to the named route “parameters”. 
    For example, if you have the route /user/:name, 
    then the “name” property is available as req.params.name. This object defaults to {}.
    
    翻译:包含映射到指定的路线“参数”属性的对象。
    例如,如果你有route/user/:name,那么“name”属性可作为req.params.name。
    该对象默认为{}。
    

    nodejs默认提供,无需载入其他中间件
    多适用于restful风格url中的参数的解析

    req.query与req.params的区别

    1. req.params包含路由参数(在URL的路径部分)
    2. req.query包含URL的查询参数(在URL的?后的参数)。

    参考博主文章地址 : https://www.cnblogs.com/jkingdom/p/8065202.html

  • 相关阅读:
    python列表转json树菜单
    lvm分区创建和扩容
    分布式网络概述
    mycat权威指南阅读笔记--序言1
    Mongodb副本集实现及读写分离
    线程和进程
    socket客户端怎么判断http响应数据的结束
    java遍历http请求request的所有参数实现方法
    Java中mongodb使用and和or的复合查询
    idea @Override is not allowed when implementing interface method
  • 原文地址:https://www.cnblogs.com/ifon/p/11372667.html
Copyright © 2011-2022 走看看