node.js获取参数的常用方法(总结)

yipeiwu_com6年前Python基础

1、req.body

2、req.query

3、req.params

一、req.body例子

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

<form action='/test' method='post'> 
  <input type='text' name='name' value='lmw'> 
  <input type='text' name='tel' value='1234567'> 
  <input type='submit' value='Submit'> 
</form>
app.post('/test', function(req, res) {
  console.log(req.body.name);
  console.log(req.body.tel);
});

 二、req.query例子

有nodejs默认提供,无需载入中间件,这个方法通常用来解析get请求中的数据

GET /test?name=lmw&tel=123456789

app.get('/test', function(req, res) {
  console.log(req.query.name);
  console.log(req.query.tel);
});

三、req.query和req.body同时使有

<form action='/test?id=1' method='post'> 
  <input type='text' name='name' value='lmw'> 
  <input type='text' name='tel' value='123456789'> 
  <input type='submit' value='Submit'> 
</form>
app.post('/test', function(req, res) {
  console.log(req.query.id);
  console.log(req.body.name);
  console.log(req.body.tel);
});

四、req.params

另一种方法传递参数给服务器,但是这不算是传统标准规范的做法,是属于 HTTP Routing 的延伸应用

GET /test/lmw/123456789

app.get('/test/:name/:tel', function(req, res) {
  console.log(req.params.name);
  console.log(req.params.tel);
});

总结:

req.query: 解析后的 url 中的 querystring,如 ?name=haha,req.query 的值为 {name: 'haha'}

req.params: 解析 url 中的占位符,如 /:name,访问 /haha,req.params 的值为 {name: 'haha'}

req.body: 解析后请求体,需使用相关的模块,如 body-parser,请求体为 {"name": "haha"},则 req.body 为 {name: 'haha'}

以上这篇node.js获取参数的常用方法(总结)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3.5装饰器原理及应用实例详解

Python3.5装饰器原理及应用实例详解

本文实例讲述了Python3.5装饰器原理及应用。分享给大家供大家参考,具体如下: 1、装饰器: (1)本质:装饰器的本质是函数,其基本语法都是用关键字def去定义的。 (2)功能:装饰...

Django urls.py重构及参数传递详解

Django urls.py重构及参数传递详解

1. 内部重构# 2. 外部重构# website/blog/urls.py website/website/urls.py 3. 两种参数处理方式 # 1. blog/ind...

操作Windows注册表的简单的Python程序制作教程

通过Python操作注册表有两种方式,第一种是通过Python的内置模块 _winreg;另一种方式就是Win32 Extension For Python 的win32api模块,但是...

用Cython加速Python到“起飞”(推荐)

用Cython加速Python到“起飞”(推荐)

事先声明,标题没有把“Python”错打成“Cython”,因为要讲的就是名为“Cython”的东西。 Cython是让Python脚本支持C语言扩展的编译器,Cython能够将Pyt...

基于Python实现定时自动给微信好友发送天气预报

基于Python实现定时自动给微信好友发送天气预报

效果图 from wxpyimport * import requests from datetimeimport datetime import time from apsche...