express路由及配置

路由

路由表示应用程序端点 (URI) 的定义以及端点响应客户机请求的方式。 有关路由的简介,请参阅基本路由

以下代码是非常基本的路由示例。


var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world');
});

路由方法

路由方法派生自 HTTP 方法之一,附加到 express 类的实例。

以下代码是为访问应用程序根目录的 GET 和 POST 方法定义的路由示例。


// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage');
});

Express 支持对应于 HTTP 方法的以下路由方法:getpostputheaddeleteoptionstracecopylockmkcolmovepurgepropfindproppatchunlockreportmkactivitycheckoutmergem-searchnotifysubscribeunsubscribepatchsearch 和 connect

要路由会转换为无效 JavaScript 变量名称的方法,请使用括号表示法。例如,app['m-search']('/', function ...

有一种特殊路由方法:app.all(),它并非派生自 HTTP 方法。该方法用于在所有请求方法的路径中装入中间件函数。

在以下示例中,无论您使用 GET、POST、PUT、DELETE 还是在 http 模块中支持的其他任何 HTTP 请求方法,都将为针对“/secret”的请求执行处理程序。


app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

路由路径

路由路径与请求方法相结合,用于定义可以在其中提出请求的端点。路由路径可以是字符串、字符串模式或正则表达式。

Express 使用 path-to-regexp 来匹配路由路径;请参阅 path-to-regexp 文档以了解定义路由路径时所有的可能性。Express Route Tester 是用于测试基本 Express 路由的便捷工具,但是它不支持模式匹配。

查询字符串不是路由路径的一部分。

以下是基于字符串的路由路径的一些示例。

此路由路径将请求与根路由 / 匹配。


app.get('/', function (req, res) {
  res.send('root');
});

此路由路径将请求与 /about 匹配。


app.get('/about', function (req, res) {
  res.send('about');
});

此路由路径将请求与 /random.text 匹配。


app.get('/random.text', function (req, res) {
  res.send('random.text');
});

以下是基于字符串模式的路由路径的一些示例。

此路由路径将匹配 acd 和 abcd


app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

此路由路径将匹配 abcdabbcdabbbcd 等。


app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});

此路由路径将匹配 abcdabxcdabRABDOMcdab123cd 等。


app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});

此路由路径将匹配 /abe 和 /abcde


app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});

字符 ?、+、* 和 () 是其正则表达式同应项的子集。基于字符串的路径按字面理解连字符 (-) 和点 (.)。

基于正则表达式的路由路径的示例:

此路由路径将匹配名称中具有“a”的所有路由。


app.get(/a/, function(req, res) {
  res.send('/a/');
});

此路由路径将匹配 butterfly 和 dragonfly,但是不匹配 butterflymandragonfly man 等。


app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

路由处理程序

您可以提供多个回调函数,以类似于中间件的行为方式来处理请求。唯一例外是这些回调函数可能调用 next('route') 来绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,在没有理由继续执行当前路由的情况下,可将控制权传递给后续路由。

路由处理程序的形式可以是一个函数、一组函数或者两者的结合,如以下示例中所示。

单个回调函数可以处理一个路由。例如:


app.get('/example/a', function (req, res) {
  res.send('Hello from A!');
});

多个回调函数可以处理一个路由(确保您指定 next 对象)。例如:


app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});

一组回调函数可以处理一个路由。例如:


var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

var cb2 = function (req, res) {
  res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);

独立函数与一组函数的组合可以处理一个路由。例如:


var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});

响应方法

下表中响应对象 (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() 为路由路径创建可链接的路由处理程序。 因为在单一位置指定路径,所以可以减少冗余和输入错误。有关路由的更多信息,请参阅 Router() 文档

以下是使用 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 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。

以下示例将路由器创建为模块,在其中装入中间件,定义一些路由,然后安装在主应用程序的路径中。

在应用程序目录中创建名为 birds.js 的路由器文件,其中包含以下内容:


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

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

接着,在应用程序中装入路由器模块:


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

此应用程序现在可处理针对 /birds 和 /birds/about 的请求,调用特定于此路由的 timeLog 中间件函数

 

express模块中的req,res参数的常用属性方法

const express = require('express'); 
const router = express.Router()
router.get('/',(req,res)=>{
    // Request
    // req.baseUrl 基础路由地址
    // req.body post发送的数据解析出来的对象
    // req.cookies 客户端发送的cookies数据
    // req.hostname 主机地址 去掉端口号
    // req.ip 查看客户端的ip地址
    // req.ips 代理的IP地址
    // req.originalUrl 对req.url的一个备份
    // req.params 在使用/:id/:name 匹配params
    // req.path 包含请求URL的路径部分
    // req.protocol http 或https协议
    // req.query 查询字符串解析出来的对象 username=zhangsan&password=123 { username:zhangsan }
    // req.route 当前匹配的路由 正则表达式
    // req.params 获取路由匹配的参数
    // req.get 获取请求header里的参数
    // req.is 判断请求的是什么类型的文件
    // req.param(key名称) 用来获取某一个路由匹配的参数
  
    //Response
    // res.headersSent 查看http响应是否响应了http头
    // res.append(名称,value) 追加http响应头
    // res.attachment(文件路径) 响应文件请求 
    // res.cookie() 设置cookie
    
    //res.setHeader('Content-Type','text/html;charset=utf8')
    // res.append('Content-Type','text/html;charset=utf8')
    // res.append('hehe','1008')
    // res.append('haha','1008')
    // res.attachment('./xx.zip') //Content-Disposition: attachment; filename="xx.zip"
    // res.clearCookie(cookiename) 删除cookie
    // res.cookie('aaa','1234') 设置cookie
    // res.cookie('aaa','1234',{
    //     maxAge:90000,
    //     httpOnly:true,
    //     path: '/admin', 
    //     secure: true,
    //     signed:true
    // })
    // res.clearCookie('aaa')
 
    // res.download(文件的path路径) 跟attachment类似 用来处理文件下载的 参数是文件地址
    // res.end http模块自带的
    // res.format()协商请求文件类型 format匹配协商的文件类型
    // res.format({
    //     'text/plain': function(){
    //         res.send('hi');
    //     },
        
    //     'text/html': function(){
    //         res.send('<p>hi</p>');
    //     },
        
    //     'application/json': function(){
    //         res.send({ message: 'hi' });
    //     },
        
    //     'default': function() {
    //         // log the request and respond with 406
    //         res.status(406).send('Not Acceptable');
    //     }
    // });
 
    // res.get('key') 获取响应header数据
    // res.json() 返回json数据 会自动设置响应header Content-type 为json格式 application/json
 
    // res.json({
    //     age:100
    // })
  
    // jsonp 利用的就是浏览器加载其他服务器的文件不会存在跨域问题
    // ajax请求就会有跨域问题
 
    // res.setHeader('Content-Type','text/javascript;charsert=utf8')
    // res.end(`typeof ${req.query.callback} == 'function' ? ${req.query.callback}({aa:100}):null`)
 
    // res.jsonp({aaa:100})
 
 
    // 重定向 把访问的地址跳转到另一个地址上
    // res.redirect(301,'/api/aes')
 
    // express jade
    // res.render('index',{title:"hehe",test:"23"})
    // res.send('') 发送数据 可以是任意类型的数据
    // res.sendFile() 发送文件的 
    // res.sendStatus(200) 设置发送时的状态码
    // res.set('Content-Type', 'text/plain') //设置响应header
    // res.status(200) // 设置状态码
    // res.type('') // 直接设置响应的文件类型
 
    // res.type('pdf')
 
    // res.send({age:100})
    // res.end('ok')
    // res.end({age:100})
 
    // res.end('你好')
  
    // res.end(req.get('Accept-Language'))
    // res.json({
    //     is:req.is('text/html')
    // })
 
    // res.json({
    //     type:req.baseUrl,
    //     hostname:req.hostname,
    //     // ip:req.ip,
    //     // ips:req.ips,
    //     // route:req.route,
    //     ct:req.get('Accept'),
    //     cs:'22'
    // })
})
 
router.get('/:id/:date',(req,res)=>{
    console.log(req.params)
    // res.json(req.params)
    res.end(req.param('date'))
})
 
router.get('/aes',(req,res)=>{
    res.json({
        type:req.baseUrl
    })
})
module.exports = router

链接: http://expressjs.com/zh-cn/guide/routing.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值