第二天总结懒了... 今天继续
通过require引入express
const express = require("express");
const app = express();
使用listen监听相应端口
app.listen(8080, () => {
console.log("express start");
});
路径匹配方法
1.匹配固定的请求方法
app.get('/',(res,req,next)=>{
res.end('END')
})
app.post('/',(res,req,next)=>{
res.end('END')
})
2.使用 app.use 请求方法不受限制
app.use((req, res, next) => {
console.log("middleware 02");
req.on('data',(data)=>{
req.body = data
})
next()
});
app.use("/home", (req, res, next) => {
console.log("home middleware 01");
console.log(req.body)
res.end('END')
});
匹配时,首先匹配第一个中间件, 之后可以通过next()方法来匹配下一个,如果未使用next()方法,后续中间件不再进行匹配
在前一个中间件中监听data,将data赋值到req.body中,可以向一个中间件传递数据
使用multer库进行文件上传相关操作
const storage = multer.diskStorage({
//设置上传文件路径
destination: (req, file, cb) => {
cb(null, "./upload/");
},
//设置上传文件名
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage,
});
app.post("/upload", upload.single("file"), (req, res, next) => {
console.log(req.files);
res.end("upload success");
});
具体设置和使用可以查看中文文档multer
使用morgan进行日志记录
具体查看文档morgan