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