express路由[1]

var express = require('express');
var app = express();
//路由方法源于 HTTP 请求方法,和 express 实例相关联

//接受localhost/的路由请求,并返回hello world
app.get("/",function(req,res){
    res.send("hello world")
})

//1  使用多个回调函数处理器路由
app.get("/example/b",function(req,res,next){
    console.log('响应到这里,但是会把信息发送给下个函数')
    next();              //next回调用下个参数的回调函数
},function()req,res{
    res.send('hello from B');
})

//2  使用回调函数数组来处理路由
app.get("/example/b",[fun1,fun2,fun3])

var fun1 = function(req, res, next){
    console.log("这是第一个fun1")
    next()
}
var fun2 = function(req, res, next){
    console.log("这是第一个fun2")
    next()
}
var fun3 = function(req, res){
    res.sed("请求响应 hello world") 
}

//3 混合使用函数和函数数组处理路由
app.get("/example/c,[fun1,fun2],fun3")
var fun1 = function(req, res, next){
    console.log("这是第一个fun1")
    next()
}
var fun2 = function(req, res, next){
    console.log("这是第一个fun2")
    next()
}
var fun3 = function(req, res){
    res.sed("请求响应 hello world") 
}

响应方法
res是响应的对象,而这个对象含有一些向客户端返回响应的方法,来终结请求响应的循环,如果在路由句柄中一个方法也不调用,来自客户端的请求会一直挂起。

res.download()          提示下载文件。
res.end()               终结响应处理流程。
res.json()              发送一个 JSON 格式的响应。
res.jsonp()             发送一个支持 JSONP 的 JSON 格式的响应。
res.redirect()          重定向请求。
res.render()            渲染视图模板。
res.send()              发送各种类型的响应。
res.sendFile            以八位字节流的形式发送文件。
res.sendStatus()        设置响应状态代码,并将其以字符串形式作为响应体的一部分发送。

app.route()链式路由句柄
对相同路由地址的请求做请求方式不一样的处理比较方便,简洁了路由句柄

    app.route('/book')
        .get(function(req, res) {
            res.send('Get a random book');
    })
        .post(function(req, res) {
            res.send('Add a book');
    })
        .put(function(req, res) {
            res.send('Update the book');
    });

express.Router()
可使用 express.Router 类创建模块化,可挂载的路由句柄。Router 实例是一个完整的中间件和路由系统。可以定义一个路由模块,并挂载至应用的路径上
如:在app.js目录下创建名为bird.js的文件,bird.js内容如下:

var express = require('express');
var router = express.Router();

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// 定义网站主页的路由
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// 定义 about 页面的路由
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

然后在app.js应用中加载路由模块

var birds = require('./birds')
....
app.use('/binds',birds)

应用即可处理发自 /birds 和 /birds/about 的请求,并且调用为该路由指定的 timeLog 中间件。

猜你喜欢

转载自blog.csdn.net/daxianghaoshuai/article/details/72729822