express是专门开发web服务器的插件
web服务器分为:
- web网站服务器
- api接口服务器
注意点:
这个给客户端发送数据是send(),不同于原生的http模块,原生的是end()是不能直接发送对象的,需要注意
首先是安装到项目,并引用
npm i express
const express = require('express')
const app = express()
简单使用
app.get('/user/:id', (request, response) => {
// end()不能直接传对象,转成字符串
//response.end('{ "name": "张三", "age": 20, "gender": "男" }')
//使用send()
response.send({ name: "张三", age: 20, gender: "男" })
//前端请求参数在request.query中
console.log(request.query)//{}这个参数形式是 http://url?key=value&key=value
// 动态参数请求地址参数在params中 /user/aaa?name=zhangsan
console.log(request.params) //{id:aaa}
})
app.post('/user', (request, response) => {
response.send('请求成功')
})
// express静态资源服务器,express在指定静态服务器中查找文件,但是目录名不会出现在url中
// 托管多个时候在没有加前缀或者前缀一样首,是按先后顺序加载静态资源的
//我查找的是test.json这个文件,实际是返回的是当前文件夹file中的test.json
app.use(express.static('./file'))//http://127.0.0.1:8081/test.json
app.use(express.static('./resources'))//http://127.0.0.1:8081/test.json
// 加入前缀区分
app.use('/ab', express.static('./file'))//http://127.0.0.1:8081/ab/test.json
app.use('/abc', express.static('./resources'))//http://127.0.0.1:8081/abc/test.json
app.listen(8081, () => {
console.log('启动成功')
})
express路由
路由是一种映射关系
在express中是前端请求与服务端接口的url
app.get('/', (request, response) => {
response.send('get请求/')
})
app.post('/', (request, response) => {
response.send('post请求/')
})
app.get('/ts', (request, response) => {
response.send('get请求/ts')
})
app.post('/ts', (request, response) => {
response.send('post请求/ts')
})
app.get('/ts/a', (request, response) => {
response.send('get请求/ts/a')
})
app.post('/ts/a', (request, response) => {
response.send('post请求/ts/a')
})
- 路由是自上而下匹配的越靠前服务权重越大
- 前端请求请求类型和url要保持一致
模块化路由
由于这么挂载当路由特别多时候文件特别大,不好维护,需要单独把路由模块化
步骤:
- 新建路由模块js
- 创建路由对象express.Router()
- 向对象上挂在路由
- 向外通过module.exports向外共享路由对象
- 使用app.use()使用模块
//路由模块
const express = require('express')
const router = express.Router()
router.get('/ts', (request, response) => {
response.end('get请求/ts')
})
router.post('/ts', (request, response) => {
response.end('post请求/ts')
})
module.exports = router
module.exports = router注意这个地方是把router整个暴露给exports,不能是module.exports = {router:router}
使用路由模块
使用app.use()
const express = require('express')
const router = require('./router')
const app = express()
app.use(router)
app.listen(8081, () => {
console.log('启动成功')
})
同时可以统一为路由添加前缀,类似与静态资源在调用app.use()的时候添加第一个参数
app.use('/api',router)