1. 程式人生 > 實用技巧 >node-express router路由的使用

node-express router路由的使用

node的express框架使得node開發簡化了很多,下面簡單介紹下簡化的點:

  • 例如:
    • 獲取請求地址引數的解析,直接轉化為物件形式;
    • express路由router的引入,使處理不同請求對應到不同的介面
    • ......

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

相信介紹完兩者的區別後,你會深有感覺,看完細看後面的express路由詳解

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