指应用程序的端点 (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')
})
支持的方法
常见的get、post、put和delete等,参考app.METHOD: https://www.expressjs.com.cn/4x/api.html
路径匹配方式
- 字符串匹配=> '/abc'
- 问好匹配 => '/ab?cd' 表示0个或1个b
- 加号匹配 => '/ab+cd' 表示一个或多个b
- 星号匹配 => '/ab*cd' 表示0个或多个字符
- 正则匹配 => '/.*fly$/' 表示匹配fly结尾的字符串
- 动态路由 => '/abc/:name' 表示name为路由传值
路由处理过程
路由通过回调函数处理对应的请求,但是在处理请求之前我们可以有多个中间件,先对最终的处理做加工,即一道工序由若干个步骤组成,最后再处理回调函数的内容。
示例
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.json 发送 JSON 响应。
- res.render 渲染视图模板。
- res.send 发送各种类型的响应。
以上便是express的路由相关,实不相瞒,想要您一个赞~