基于 Node.js 平台,快速、开放、极简的 Web 开发框架
express安装
- 创建pagejson 文件
cnpm init -yes
- 安装express
cnpm install express --save-dev
- 引入express
let express = require('express');
express创建框架服务器
- 创建express框架实例
let app = express();
let app = new express();
- 监听服务器端口
//引入路由模块
let firstpageRoute = require('./routes/firstPage');
//监听服务器端口
app.listen(8000, 'localhost', () => {
console.log("服务器启动成功!","http://localhost:8000");
});
- 使用路由模块app.use()
直接添加路由模块app.use(firstpageRoute);
主路由:关联的时候给当前路由模块添加路由路径app.use('/index', firstpageRoute);
配置框架路由 all get post
1. all 全局路由守卫
all用于所有的http请求 ,类似每个路由的安全守卫,路由守卫提前路由执行
all里面写路径'/'
指当前路由的守卫,写'*'
指所有的路由守卫
app.all('/', (req, res, next) => {
console.log("定位路由");
next();
});
2. get 地址访问
get 传值 req.query
app.get("/", (req, res) => {
res.send("express框架 get路由"+res.send(JSON.stringify(req.query)));
});
路由的线路
数组方法
3. post 表单提交
app.post("/login", (req, res) => {
res.send("express框架 post路由");
});
4. 正则匹配路由路径
REG path | Request URL |
---|---|
/logo? | ?匹配前面的子表达式0次或者1次 /log /logo |
/logo+ | +匹配前面的子表达式1次或者多次 /logo /logoo … |
/lo*go | *匹配前面的子表达式0次或者多次 保证输入和 表达式结尾一致 |
/logo/ | 只要URL里面包含字符的路径 |
/.*fly$/ | any str +fly结尾 |
5. 路由的动态传值
传值req.params
渲染页面 res.send(JSON.stringify(req.paramas))
Route path | Request URL |
---|---|
/:from.:to | http://localhost:8000/FROM.EXp {“from”:“FROM”,“to”:“EXp”} |
/:from-:to | http://localhost:8000/fromstr-tostr |
可以进行正则验证格式 \ 得转义 /user/:userid(\\d+) | http://localhost:8000/user/任意数字 |
6. 模块化路由app.route()
重定向路由 res.redirect('/index/');
7. 快速路由
8.路由的线路
- 类似路由的守卫功能,一个路由可以执行多个回调函数
app.get("/", (req, res, next) => {
console.log("在regest里面检测");
next();
}, (req, res, next) => {
console.log("再次检测");
next();
}, (req, res) => {
res.send("注册界面");
});
- 将路由的线路 做成数组
let fun1=(req,res,next)=>{
console.log(1);
next();
}
let fun2=(req,res,next)=>{
console.log(2);
res.send("注册");
}
app.get("/",[fun1,fun2]);
- 同名路由 组合线路
跳过剩余的路由回调函数,执行下一个同名路由next('route');
app.get("/", (req, res, next) => {
console.log(1);
next();
}, (req, res, next) => {
console.log(2);
if("条件") { next(); }
else{ //失败 跳过后面函数,执行下一个同名路由
// 跳过剩余的路由回调 执行下一个同名路由
next('route');
}
}, (req, res, next) => {
console.log(3);
next();
});
app.get("/", (req, res, next) => {
console.log(4);
next();
}, (req, res, next) => {
console.log(5);
next();
}, (req, res) => {
console.log(6);
res.send("regest");
});