什么是express:?
地址:https://www.expressjs.com.cn/
安裝:npm i express -D
創(chuàng)建web服務(wù)器
express監(jiān)聽get post請求
get請求:
post請求
send()方法 返回請求
獲取url中的參數(shù):req.query中
獲取url中動態(tài)參數(shù):req.params
express靜態(tài)資源托管?express.static()
把目錄所有文件為靜態(tài)資源
```js
const express = require('express');
const app = express();
// 文件夾路徑
app.use(express.static('./PluginVideo'))
// 托管多個多次調(diào)用static
// 啟動服務(wù)器
app.listen(80, () => {
? ? console.log('啟動成功:http://127.0.0.1')
})
```
掛載路徑前綴app.use('',express.static())
nodemon監(jiān)聽代碼改動
express路由
const express=requier('express');
const app=express();
最簡單的用法app.get()? app.post():不推薦使用
通過
模塊化路由
將路由處理為單獨(dú)模塊
express.Ruoter()創(chuàng)建路由對象
moudel.exports共享對象
app.use注冊對象
創(chuàng)建:
// 模塊化路由對象
const experss = require('experss');
const router = experss.Router()
// router掛載路由
router.get('/user', (req, res) => {
? ? console.log('成功')
? ? res.send({
? ? ? ? name: '成功'
? ? })
})
// 共享
module.exports = router
導(dǎo)入注冊模塊:
app.use:用來注冊中間件的
const express = require('express');
const app = express();
// 引入路由模塊
const router = require('./router');
// 注冊模塊路由
app.use(router)
// 啟動服務(wù)器
app.listen(80, () => {
? ? console.log('服務(wù)器啟動:http://127.0.0.1')
})
為路由模塊添加統(tǒng)一的訪問前綴:app.use(‘前綴’,路由)逆屡;
中間件:
中間件的調(diào)用流程:
express中間件的格式:
next()的作用:是實(shí)現(xiàn)多個中間件函數(shù)的關(guān)鍵圾旨;
1:定義中間件函數(shù):
全局生效的中間件:使用use注冊就行
定義全局中間件的簡化方式:app.use((req,res,next)=>{});
中間件的作用:
定義多個連續(xù)中間件:
局部調(diào)用中間件:
app.get('/use','中間件函數(shù)',(req,res)=>{? ?})
定義多個局部中間件函數(shù):
注意事項(xiàng):
中間件必須放在路由前面魏蔗;客戶端可以多個中間件碳胳;不能忘記一點(diǎn)調(diào)用next();
寫完next后別再寫代碼了沫勿;連續(xù)調(diào)用多個中間件的時候中間件req,res可以共享;
中間件分類:
路由級別中間件:
錯誤級別中間件:
錯誤級別中間件必須放在所有路由之后味混;
express內(nèi)置中間件:
experss.json
第三方中間件:
自定義中間件:
使用req.on()監(jiān)聽事件
使用experss寫接口:
創(chuàng)建路由模塊
解決接口跨域問題:
CORS解決方法:
一定要在路由之前掛載注冊