Node.js express框架--路由

基于 Node.js 平台,快速、开放、极简的 Web 开发框架

express安装

  1. 创建pagejson 文件 cnpm init -yes
  2. 安装express cnpm install express --save-dev
  3. 引入express let express = require('express');

express创建框架服务器

  1. 创建express框架实例
    let app = express(); let app = new express();
  2. 监听服务器端口
//引入路由模块
let firstpageRoute = require('./routes/firstPage');
//监听服务器端口
app.listen(8000, 'localhost', () => {
    console.log("服务器启动成功!","http://localhost:8000"); 
});
  1. 使用路由模块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 pathRequest 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 pathRequest URL
/:from.:tohttp://localhost:8000/FROM.EXp
{“from”:“FROM”,“to”:“EXp”}
/:from-:tohttp://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");
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值