node-express router路由的使用

node的express框架使得node开发简化了很多,下面简单介绍下简化的点:

  • 例如:
    • 获取请求地址参数的解析,直接转化为对象形式;
    • express路由router的引入,使处理不同请求对应到不同的接口
    • ......

一、原始路由和express的路由对比

相信介绍完两者的区别后,你会深有感觉,看完细看后面的express路由详解

原始路由请参考 https://i.cnblogs.com/posts/edit;postId=13278803

1、原始路由描述:原始路由通过判断res.url对象里面的pathname来判断进入哪个接口

前台处理请求路径进行处理,需要过滤掉/favicon.ico,再字符串截取,总体来说很麻烦

var { pathname, query } = url.parse(req.url);
pathname = pathname.substr(1);
    if (pathname != 'favicon.ico') {
        try {
            if(pathname.indexOf('images')==-1){
                route[pathname](req, res);
            }else{
                path = pathname.split('/')[1];
                route['images'](path,req, res);
            }
         } catch (e) {
                route['noFound'](req, res);
         }
    }
}

node后台路由文件

module.exports = {
    //请求地址对应localhost:8081/home
    home: function (req, res) {
        res.write('<h1>home</h1>')
    },
    //请求地址对应localhost:8081/login
    login: function (req, res) {
        res.write('<h1>login</h1>')
    },
    //请求地址对应localhost:8081/rest
    rest: function (req, res) {
        res.write('<h1>rest</h1>');
    },
    //请求地址不存在
    noFound: function (req, res) {
        res.write('<h1>404-页面未找到</h1>');
    }
}

2、express框架的路由会根据前期路径快速匹配不同的接口

//请求地址对应localhost:8081
router.get('/', function (req, res, next) {    
    res.send();
});
//请求地址对应localhost:8081/login
router.get('/login', function (req, res, next) {    
    res.send();
});

二、express路由的使用

实现请正确安装好express,使用以下代码即可实现路由

主文件app.js代码

//  app.js 首页
const express = require('express');
const app = express();
const login = require('./router/login')  //  引入路由文件


//设置跨域访问
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
//  使用路由 /login是路由指向名称
app.use('/',login) //对应上面引入的路由文件,一对一

//配置服务端口 
var server = app.listen(8081, () => {
    const hostname = 'localhost';
    const port = 8081;
    console.log(`Server running at http://${hostname}:${port}/`);
})

路由文件代码

const express = require(`express`)
const router = express.Router()

router.use((req, res, next) => {
    // console.log(`路由执行成功啦~~~`, Date.now());
    next();
})

//请求路径对应于localhost:8081      此处是重点
router.get('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
        res.send();
    });
})

//请求路径对应于localhost:8081/login   此处是重点
router.get('/login', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
        res.send();
    });
})

//请求路径对应于localhost:8081/main      此处是重点
router.get('/main', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
        res.send();
    });
})
module.exports = router
posted @ 2020-07-16 20:14  飘逸_winxin  阅读(1096)  评论(0编辑  收藏  举报