前端我们知道,一个域名后面跟的pathname可以作为特殊内容去请求后端资源,那么,后端是如何识别这个pathname,并执行到对应的流程呢?node的路由自然映射便可以解决这个问题!
自然映射
我们需要新建文件controller/user.js
const getUser1 = (req,res) => {
res.end('get user1')
}
const getUser2 = (req,res) => {
res.end('get user2')
}
module.exports = {
'user-head': getUser1,
'user-body': getUser2
}
这里的导出的对象key,实际上对应路由的一个层级,如localhost:8138/user-head
然后和controller文件夹同级,建立index.js
const http = require('http');
const url = require('url');
const port = 8138;
const hostname = '127.0.0.1';
const natureMap = (req,res) => {
const pathname = url.parse(req.url).pathname;
const paths = pathname.split('/');
const controller = paths[1] || 'index';
const action = paths[2] || 'index';
const args = paths.slice(3);
let module;
try {
// module的缓存机制使得只有第一次是阻塞的
module = require('./controller/' + controller);
console.log(module,'-=-=')
} catch(err) {
res.end('500');
return;
}
const method = module[action];
if ( method ) {
method.apply(null,[req,res].concat(args));
} else {
res.end('500-1')
}
}
const server = http.createServer((req,res) => {
natureMap(req,res)
// res.end('ok')
})
server.listen(port,hostname,() => {
console.log(`its running: http://${hostname}:${port}`,)
})
仔细看natureMap方法,我们会发现我们将url上的pathname的前两个层级,一个用于查找路由文件,另一个查找对应的action,而之后的层级则作为参数传给了对应的action
method.apply(null,[req,res].concat(args));
自然映射的核心是,利用require功能,导入对应文件的action,因此我们在controller文件夹下会建立很多控制器;
后端会约定pathname的第一个参数为寻找controller,第二个参数为对应的action路径,第三个往后为params;因此我们这里的 controller/user.js;下面倒出模式为module.exports = { 'user-haed': getUser1, 'user-body': getUser2 }
当找到了对应的action之后,通过apply执行该方法,同时把req,res和参数传给对应的action:method.apply(null,[req,res].concat(args));
以上,便是node的自然映射,实不相瞒,我想要一个赞!!!