express 是一个基于nodejs的开发框架
- 安装express
-
yarn add express
-
yarn global add express-generator //express 脚手架
-
- express的核心 -- app
const express = require('express')
const app = express()
- app.use 首先,我们看一下app.use的最简单的用法
app.use((request,response,next)=>{
console.log(request.path)
response.send('hello world!')
next()
})
此时,后端会打印出我们访问的路径 例如:http://localhost:3000/ 会打印出 "/",前端会显示hello world!
我们会发现,他和原生node十分相似
const http = require('http')
const server = http.createServer()
server.on('request', (request, response)=>{
console.log(request)
response.end('hello world!')
})
server.listen('3000')
所以,express其实就是对node进行了一些封装。
- 当有多个app.use时,我们应该怎么办 对于express的编程模型来说,每一个use就是在队列中插入一个函数,当调用next之后,才会执行后面的代码,而use中的函数,我们也可以称之为中间件。
const express = require('express')
const app = express()
app.use((req,res,next)=>{
console.log('第一个app.use')
res.write('hello world!');
next()
})
app.use((req,res,next)=>{
console.log('第一个app.use')
res.write('hello world!');
res.end()
})
我们看到,当一个app.use结束之后,我们需要调用一下next,并且由于response.send只能被调用一次,所以我们选择使用stream的方式,response.write来写内容
- express的路由
- 单的路由实现方式
const express = require('express')
const app = express()
app.use((request,response,next)=>{
if(request.path === '/'){
response.write('index')
}else if(request.path === '/home'){
response.write('home')
}
response.end()
})
- 使用语法糖
- app.use('/xxx',fn)
const express = require('express')
const app = express()
app.use('/xxx', (request,response,next)=>{
response.send('xxx')
next()
})
- app.get('/xxx',fn) 只会接受get请求
const express = require('express')
const app = express()
app.get('/xxx', (request,response,next)=>{
response.send('xxx')
next()
})
-
app.post('/xxx',fn) 只会接受post请求
-
app.route('/xxx').all(fn1).get(fn2).post(fn3)
const express = require('express')
const app = express()
app.route('/xxx')
.all((request,response,next)=>{
response.write('all')
next()
})
.get((request,response,next)=>{
if(request.method === 'GET'){
response.write('get')
response.end()
}else{
next()
}
})
.post((request,response,next)=>{
if(request.method === 'POST'){
response.write('post')
response.end()
}else{
next()
}
})
-
错误处理
-
抛错
app.use((req,res,next)=>{
next(new Error('未登录'))
})
- 向next内传值
app.use((req,res,next)=>{
next('未登录')
})
接受错误
app.use((err,req,res,next)=>{
res.write('err')
next(err)
})
const express = require('express')
const app = express()
app.use((request,response,next)=>{
next('未登录')
})
app.use((error,request,response,next)=>{
console.log('错误处理1')
next(error)
})
app.use((error,request,response,next)=>{
console.log('错误处理2')
response.end()
})