1:Express简介
-基于Node的极简MVC框架
- 提供灵活的路由功能
- 提供强大的中间件机制
- 内核极小、扩展性很好(使用广泛)
2:路由机制
Express概念:定义了Api的地址,请求、响应方式
方法:天然支持HTTP Method 中的某个方法,Get/Post等
3:中间件机制
Express中间件:
- Express应用的基本组成单元
- 中间件都有req、res、next参数
req:包含当前请求的所有请求的参数以及后端的一些信息
res:对当前请求的响应信息
next:控制后端流向的机制(当使用next后,后续中间件将会被执行,否则不会)
- 可处理业务,修改req、修改res、结束响应,传到下一个
- 内置中间件,可使用第三方中间件
4:实例Demo--Serve静态文件
主入口文件:app.js
// 引用相关的库
var express=require('express');
// 创建一个应用
var app= express();
/*
使用express的第三方中间件来创建静态资源文件
*/
app.use(express.static('./public'));
function middleware1(req,res,next){
if(req.query.chain){
res.message='hello middleware1 \n';
next();
}
else{
res.send('Hort from middleware1');
}
}
function middleware2(req,res,next){
res.message+='hello middleware2 /n';
next();
}
app.get('/',middleware1,middleware2,function(req,res,next) {
res.send(res.message+'hello middleware3,today is fine!');
});
app.get('/home',function (req,res,next) {
// body...
res.send('hello ,This Page is Home ,and you will get what you want!!!');
});
app.post('/someUrl',function(req, res, next) {
/*optional stuff to do after success */
res.send('hello express,this is the someUrl Page![POST]');
});
app.listen(3000);
console.log('express server is starting at port 3000');
文件结构:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>serve file serverd from express's static middleware!</h1>
</body>
</html>
style.css:
body{
background:black;
color:white;
}
script.js:
alert('hello')
最终效果:
OK,关于Express的入门就介绍到这里,又更好的想法的大佬,欢迎来交流