一、安裝express
npm i express
二、express應(yīng)用
1.導(dǎo)入express
const express = require("express")
2.實(shí)例化express
const app = express()
3.監(jiān)聽(tīng)訪(fǎng)問(wèn)并響應(yīng)
//user 接口名
//req 請(qǐng)求對(duì)象
//res 響應(yīng)對(duì)象
//res.send 響應(yīng)內(nèi)容
get請(qǐng)求
app.get("/user",(req,res) => {
res.send({
status:200
})
})
post請(qǐng)求
app.post("/user", (req,res) => {
res.send({
status:200
})
})
4.啟動(dòng)express
app.listen(80,() => {
console.log("http://127.0.0.1")
})
以上是最簡(jiǎn)單的express的應(yīng)用
三、express的進(jìn)一步使用
1.router的使用
項(xiàng)目中請(qǐng)求接口較多,可以將項(xiàng)目的請(qǐng)求單獨(dú)抽離出來(lái)。如:router.js
1)導(dǎo)入router
const express = require("express")
2)實(shí)例化router
const router = express.Router()
3)使用router監(jiān)聽(tīng)接口訪(fǎng)問(wèn)并響應(yīng)
router.get("/user",(req,res) => {
res.send({
status:200
})
})
post請(qǐng)求
router.post("/user", (req,res) => {
res.send({
status:200
})
})
4)導(dǎo)出router
module.exports = router
5)將router掛在到express上
const router = require("./router")
app.use(router)
2.中間件的使用
中間件可以對(duì)請(qǐng)求數(shù)據(jù)進(jìn)行處理,之后可以將處理的內(nèi)容交給下一個(gè)中間件或者接口監(jiān)聽(tīng)函數(shù)進(jìn)行處理
中間間函數(shù)比接口監(jiān)聽(tīng)函數(shù)多了一個(gè)next參數(shù)
1)全局中間件
app.use((req,res,next) => {
console.log("全局中間件")
next()
})
2)局部中間件
router.get("/user",(req,res,next) => {
console.log("局部中間件")
next()
})
3)內(nèi)置中間件
//對(duì)json格式的請(qǐng)求體數(shù)據(jù)進(jìn)行處理,使用后可以在req.body中獲取請(qǐng)求體中數(shù)據(jù)
app.use(express.json())
//對(duì)x-www-form-urlencode格式的請(qǐng)求體數(shù)據(jù)進(jìn)行處理,使用后可以在req.body中獲取請(qǐng)求體中數(shù)據(jù)
app.use(express.urlencoded({extended:false}))
4)第三方中間件
npm i body-parser
const parser = require("body-parser")
app.use(parser.urlencoded({extends:false}))
5)處理錯(cuò)誤的中間件
處理項(xiàng)目中出現(xiàn)的錯(cuò)誤,比一般的中間件多了個(gè)error參數(shù)
app.use((error,req,res,next) => {
res.send(error.message)
})
3.使用中間件處理跨域問(wèn)題
//設(shè)置跨域訪(fǎng)問(wèn)
app.use(function(req, res, next) {
console.log("跨域")
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With,X-Tag");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});