@JunQiu
2018-09-18T09:48:31.000000Z
字数 3342
阅读 1632
summary_2018/06 express
### Examplevar express = require('express')var app = express()// respond with "hello world" when a GET request is made to the homepageapp.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.jsvar express = require('express')var router = express.Router()// middleware that is specific to this routerrouter.use(function timeLog (req, res, next) {console.log('Time: ', Date.now())next()})// define the about routerouter.get('/about', function (req, res) {res.send('About birds')})module.exports = router//在应用程序中加载路由器模块var birds = require('./birds')//http://127.0.0.1:4000/birds/aboutapp.use('/birds', birds)### 路由参数Route path: /users/:userId/books/:bookIdRequest URL: http://localhost:3000/users/34/books/8989req.params: { "userId": "34", "bookId": "8989" }//querystring,支持asyncapp.get('/ins', async (req, res) => {console.log(req.query)}### responseMethodMethod Descriptionres.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.jsmodule.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 routeif (req.params.id === '0') next('route')// otherwise pass the control to the next middleware function in this stackelse next()}, function (req, res, next) {// render a regular pageres.render('regular')})Tips:跳过路由器中间件堆栈中的其余中间件功能,调用next('route')以将控制权传递给下一个路由。仅适用于使用app.METHOD()或router.METHOD()功能加载的中间件功能。// handler for the /user/:id path, which renders a special pageapp.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!')})#### 内置中间件和第三方中间件
