【NodeJs基础篇】(十一)Express 4.x中request参数的获取

基本上每个Http服务器的编程框架都是对requestresponse的处理。即处理浏览器对服务器的请求(request)和服务器对浏览器的响应(response)。node

request是浏览器给服务器的请求,通常用到的是两种方法:PostGet(Express也支持其它方法,如put)。两种方法都会指定路由,除此以外,Get方法的使用场景是浏览器向服务器请求数据,好比访问首页,即向浏览器请求首页内容,能够带参数指定须要哪些内容,因此咱们须要既能获取路由还能获取参数;Post指的是向服务器推送内容,而后得到一个反馈,因此咱们须要能获取Post的内容。git

request提供了三种方法来获取参数和内容:request.params,request.query,request.bodygithub

Github源码下载web

request.params方法

params方法用于从express路由器获取参数,示例以下:express

app.get('/find/:id', function(req,res){
    console.log(req.params.id);
    res.send(req.params.id);
})

而后在浏览器访问 http://localhost:3000/find/1npm

便可以看到控制台输出了1,同时界面上也显示1.编程

若是有多个参数,能够这样设置:/find/:group/:name,示例:json

// params example2
app.get('/find/:group/:name', function(req, res) {
    console.log(req.params.group+" "+req.params.name);
    res.send(req.params.group+" "+req.params.name);
})

在浏览器访问:http://localhost:3000/find/a/b后端

request.query方法

request.query获取?后的查询参数,很简单,示例以下:浏览器

app.get('/search', function(req, res){
    console.log(req.query.id)
    res.send(req.query.id)
})

访问示例:http://localhost:3000/search?id=1&name=a

request.body

上述两个都是获取的get参数,下面获取一下Post的内容。目前,常见使用Post提交的场景有两个,表单提交和Ajax。下面以Ajax为例,介绍如何使用获取Post中的参数。

构造一个Ajax Post:

$.post("/add", {sid:sid});

向服务器提交sid。

后端代码以下:

var bodyParser = require("body-parser")
...
app.use(bodyParser.urlencoded({extended:true}))
...
app.post('/add', function(req, res) {
    var sid = req.body.sid;
    console.log(sid)
});

这里出现了一个新东西,bodyParser,在express 4.x中,咱们须要单独引入bodyParser做为post body的解析器。在https://github.com/expressjs/body-parser 有这个模块的详细介绍。

若是是json数据提交,须要使用bodyParser.json(),文本则需bodyParser.text()(此时req.body的类型变成了字符串)。这两种在源码里均有测试。


源码地址:https://github.com/zgljl2012/express-learn
打开服务器:

npm install
node app.js