express

express 基于 Node.js 平台,快速、开放、极简的 Web 开发框架
文档

安装

1
npm install express

启动服务

1
2
3
4
5
6
7
8
const server = require('express')();
server.get('/', function (req, res, next) {
//do something
// next()
})
server.listen(8084,()=>{
console.log('server is on port 8084')
});

router

app.METHOD(PATH, HANDLER)

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
    1
    2
    3
    app.get('/', function (req, res) {
    res.send('hello world')
    })

middleware 中间件

use
1
2
3
4
5
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
Built-in middleware
  • express.static serves static assets such as HTML files, images, and so on.
  • express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+
  • express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+

static

1
2
3
4
5
6
let options = {
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
server.use(express.static('public', options))

模板 template engines

pug

1
npm install pug
1
2
3
4
5
//serve.js
server.set('view engine', 'pug')
server.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})

pug

调试DEBUG

1
2
3
4
# lunix:
DEBUG=express:* node index.js
# window:
set DEBUG=express:* & node index.js

更多文档,请查看官方4x文档