时间:2023-05-25 04:09:02 | 来源:网站运营
时间:2023-05-25 04:09:02 来源:网站运营
Node.js——express开发web服务器:npm install -g express-generator
创建项目:express express-demo
项目目录如下:├── app.js├── bin│ └── www├── package-lock.json├── package.json├── public│ ├── images│ ├── javascripts│ └── stylesheets│ └── style.css├── routes│ ├── index.js│ └── users.js└── views ├── error.jade ├── index.jade └── layout.jade
我们可以安装依赖,将程序跑起来:npm installnode bin/www
方式二:从零学习搭建npm init -y
express的安装:release
版本是4.17.1,我们使用该版本;npm install express
const express = require('express');// 创建服务器const app = express();// /home的get请求处理app.get("/home", (req, res) => { res.end("Hello Home");});// /login的post请求处理app.post("/login", (req, res) => { res.end("Hello Login");});// 开启监听app.listen(8000, () => { console.log("服务器启动成功~");})
我们会发现,之后的开发过程中,可以方便的将请求进行分离:/users/:userId
;request
对象中要获取可以通过 req.params.userId
;res.json(数据)
方式;const express = require('express');const app = express();app.get('/users/:userId', (req, res, next) => { console.log(req.params.userId); res.json({username: "coderwhy", level: 99});});app.listen(8000, () => { console.log("静态服务器启动成功~");})
请求-响应周期
(返回数据);请求-响应周期
,则必须调用next()将控制权传递给下一个中间件功能,否则,请求将被挂起。app/router.use
和app/router.methods
;app.get或app.post
等;const express = require('express');const app = express();app.use((req, res, next) => { console.log("common middleware 01"); next();})app.use((req, res, next) => { console.log("common middleware 02"); res.end("Hello Common Middleware~");})app.listen(8000, () => { console.log("中间件服务器启动成功~");})
中间件的执行顺序:// 案例二: 路径匹配中间件app.use('/home', (req, res, next) => { console.log("home middleware 01"); next();});app.use('/home', (req, res, next) => { console.log("home middleware 02"); next(); res.end("Hello Home middleware");});app.use((req, res, next) => { console.log("common middleware");});
案例三:path和method匹配中间件// 案例三: method匹配中间件app.get('/home', (req, res, next) => { console.log("home get middleware"); next();})app.post('/login', (req, res, next) => { console.log("login post middleware"); next();});app.use((req, res, next) => { console.log("common middleware");});
案例四:注册多个中间件// 案例四: 注册多个中间件const homeMiddleware1 = (req, res, next) => { console.log('home middleware 01'); next();}const homeMiddleware2 = (req, res, next) => { console.log('home middleware 02'); next();}const homeHandle = (req, res, next) => { res.end("Hello Home~");}app.get('/home', homeMiddleware1, homeMiddleware2, homeHandle);
app.post('/login', (req, res, next) => { req.on('data', (data) => { console.log(data.toString()); }) req.on('end', () => { res.end("登录成功~"); });});
我们也可以自己编写中间件来解析JSON:app.use((req, res, next) => { if (req.headers['content-type'] === 'application/json') { req.on('data', (data) => { const userInfo = JSON.parse(data.toString()); req.body = userInfo; }) req.on('end', () => { next(); }) } else { next(); }})app.post('/login', (req, res, next) => { console.log(req.body); res.end("登录成功~");});
但是,事实上我们可以使用expres内置的中间件或者使用body-parser
来完成:app.use(express.json());app.post('/login', (req, res, next) => { console.log(req.body); res.end("登录成功~");});
如果我们解析的是 application/x-www-form-urlencoded
:urlencoded
函数来作为中间件:app.use(express.json());app.use(express.urlencoded({extended: true}));app.post('/login', (req, res, next) => { console.log(req.body); res.end("登录成功~");});
npm install morgan
直接作为中间件使用即可:const loggerWriter = fs.createWriteStream('./log/access.log', { flags: 'a+'})app.use(morgan('combined', {stream: loggerWriter}));
npm install multer
上传文件,并且默认文件名:const upload = multer({ dest: "uploads/"})app.post('/upload', upload.single('file'), (req, res, next) => { console.log(req.file.buffer); res.end("文件上传成功~");})
添加文件名后缀:const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, "uploads/") }, 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.file.buffer); res.end("文件上传成功~");})
我们也可以上传多张图片:app.use('/upload', upload.array('files'), (req, res, next) => { console.log(req.files);});
如果我们希望借助于multer帮助我们解析一些form-data中的普通数据,那么我们可以使用any:app.use(upload.any());app.use('/login', (req, res, next) => { console.log(req.body);});
app.use('/login/:id/:name', (req, res, next) => { console.log(req.params); res.json("请求成功~");})
方式二:queryapp.use('/login', (req, res, next) => { console.log(req.query); res.json("请求成功~");})
response.end
方法,用法是一致的res.end("Hello World");
json方法res.json({name: "why", age: 18});
status方法res.status(204);
express.Router
来创建一个路由处理程序:迷你应用程序
(mini-app);// 用户相关的处理const userRouter = express.Router();userRouter.get('/', (req, res, next) => { res.end("用户列表");});userRouter.post('/', (req, res, next) => { res.end("创建用户");});userRouter.delete('/', (req, res, next) => { res.end("删除用户");});app.use('/users', userRouter);
当然,我们可以配置更多的路由,并且将所有的逻辑放到一个单独的文件中。const express = require('express');const app = express();app.use(express.static('./build'));app.listen(8000, () => { console.log("静态服务器启动成功~");})
app.use((req, res, next) => { next(new Error("USER DOES NOT EXISTS"));});app.use((err, req, res, next) => { const message = err.message; switch (message) { case "USER DOES NOT EXISTS": res.status(400).json({message}) } res.status(500)})
express
函数的本质其实是createApplication
:关键词:服务