搭建express服务
npm安装express框架
npm install express --save
新建app.js文件
const express = require("express")
const http = require("http")
const app = express()
const server = http.createServer(app)
server.listen('8888')
app.use('/', (req, res) => {
res.end('hello express')
})
中间件
上面代码中,app.use()为一个中间件,第一个参数(非必选)匹配url文件路径,如localhost:8808/shop中将会匹配'/shop',匹配成功执行回调函数,匹配失败则跳过此中间件。app.use('/')匹配任意文件路径,中间件将按代码顺序依次执行
app.use('/shop', (req, res, next) => { // 匹配请求中文件路径以'/shop'开头的url
console.log('shop')
next() // 需要执行next()进行下一步
})
app.get('/shop', (req, res, next) => { // 只匹配get请求中文件路径以'/shop'开头的url
console.log('shop1')
console.log(req.query) // 获取get请求中请求参数,json对象形式
next()
})
app.post('/shop', (req, res, next) => { // 只匹配post请求中文件路径以'/shop'开头的url
console.log('shop2')
next()
})
获取post请求参数
安装body-parser模块,用于处理以x-www-form-urlencoded、json传输的数据
npm install body-parser --save
const express = require("express")
const http = require("http")
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
const server = http.createServer(app)
server.listen('8888')
app.post('/shop', (req, res, next) => {
console.log(req.body) // post请求中的数据,json形式
next()
})
app.use((req, res) => {
res.end('hello express')
})
使用中间件的其他形式(不匹配文件路径),中间件中的req,res都是公用的,可进行数据的传递
function middleware1 () {
return function (req, res, next) {
req.array = [] // 为req对象添加array属性(数组类型)
console.log('middleware1')
next()
}
}
function middleware2 (req, res, next) {
req.array.push(1)
console.log('middleware2')
next()
}
function middleware3 (req, res, next) {
req.array.push(2)
console.log('middleware3')
next()
}
app.use(middleware1(), [middleware2, middleware3])
app.use([middleware1(), middleware2, middleware3])
app.use((req, res) => {
console.log(req.array) // 输出 [1, 2]
})
中间件错误处理
...