@JunQiu
2018-09-18T17:48:31.000000Z
字数 3342
阅读 1255
summary_2018/06
express
### Example
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')
})
### Route paths(支持正则表达式)
//路径将匹配/abe并/abcde。
app.get('/ab(cd)?e', function (req, res) {
res.send('ab(cd)?e')
})
### 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(一个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 about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
//在应用程序中加载路由器模块
var birds = require('./birds')
//http://127.0.0.1:4000/birds/about
app.use('/birds', birds)
### 路由参数
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
//querystring,支持async
app.get('/ins', async (req, res) => {
console.log(req.query)
}
### responseMethod
Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.
var express = require('express')
var app = express()
//定义中间件
var requestTime = function (req, res, next) {
req.requestTime = Date.now()
next()
}
//使用中间件
app.use(requestTime)
app.get('/', function (req, res) {
var responseText = 'Hello World!<br>'
responseText += '<small>Requested at: ' + req.requestTime + '</small>'
res.send(responseText)
})
app.listen(3000)
### 可配置的中间件(传递参数)
文件: my-middleware.js
module.exports = function(options) {
return function(req, res, next) {
// 根据参数配置
next()
}
}
使用中间件,如下所示。
var mw = require('./my-middleware.js')
app.use(mw({ option1: '1', option2: '2' }))
### 中间件堆栈
app.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
#### 应用程序级
var app = express()
//没有路由功能,任何应用程序收到都会执行
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
// /user/:id路径上安装的中间件功能
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
//路由器中间件堆栈
app.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route')
// otherwise pass the control to the next middleware function in this stack
else next()
}, function (req, res, next) {
// render a regular page
res.render('regular')
})
Tips:跳过路由器中间件堆栈中的其余中间件功能,调用next('route')以将控制权传递给下一个路由。仅适用于使用app.METHOD()或router.METHOD()功能加载的中间件功能。
// handler for the /user/:id path, which renders a special page
app.get('/user/:id', function (req, res, next) {
res.render('special')
})
#### 路由级中间件
//由器级中间件的工作方式与应用级中间件的工作方式相同,只是它绑定到一个实例express.Router()。
#### 错误处理中间件
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
#### 内置中间件和第三方中间件