const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
使用 TypeScript
准备工作
-
yarn global add typescript ts-node
全局安装工具 -
yarn add @types/express
安装类型支持 tsc --init
- 修改 tsconfig的
target
和nolmplicitAny
- 将
require
改为import
运行
ts-node app2.ts
路由
使用 app.use 如何实现路由
const express = require('express')
const app = express()
app.use((request,response, next)=> {
if (request.path === '/' && request.method === 'get') {
response.send('根目录')
}
next()
})
app.use('/xxx', (request, response, next) => {
response.send('这是 xxx')
next()
})
app.get('/aaa', (request, response, next) => {
response.send('这是 aaa')
next()
})
app.listen(3000, ()=> {
console.log('正在listen 3000');
})
更方便的写法
app.use('/xxx',fn)
app.get('/xxx',fn)
app.post('/xxx',fn)
app.route('/xxx').all(f1).get(f2).post(f3)
这些都是 API 糖
错误处理
next()能传参数吗?
- 你可以看文档,也可以看TypeScript定义
- 推荐后者
next(error)
- 会直接进入errorHandler,不执行后面的中间件
- errorHandler的默认实现见文档
如何自定义errorHandler
- 还是看文档,文档说一般在最后定义
app.use((err, req, res, next) => {})
- 可以定义多个这样的中间件
onst express = require('express')
const app = express()
app.use((request, response, next) => {
response.write('1')
next()
})
app.use((request, response, next) => {
response.write('2')
if (true) {
next('error msg')
} else {
next()
}
})
app.use((request, response, next) => {
response.write('3')
next()
})
app.use((error,request, response, next) => {
response.write(error)
response.end()
next()
})
app.listen(3000, ()=> {
console.log('正在listen 3000');
})