node.js 学习四 之 路由

路由就是根据浏览器的url对应访问不同的网页
服务器拿到浏览器的url,根据正则匹配,拿到根目录之后的字符串
有一个可能名字为route.js的匹配规则,根据字符串调用不同的方法
在方法里再去读取相应的html文件,做相应的操作

04_route.js

var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function(request, response) {
    response.writeHead(200, { 'Content-Type': 'text/html;    charset=utf-8' });
    if (request.url !== "/favicon.ico") {
        var pathname = url.parse(request.url).pathname;
        console.log(pathname);
        pathname = pathname.replace(/\//, ''); //替换掉前面的/
        console.log(pathname);
        router[pathname](request, response);
        response.end('');
    }
}).listen(8000);
console.log('Server    running    at    http://127.0.0.1:8000/');

router.js

module.exports = {
    login: function(req, res) {
        res.write("我是login方法");
    },
    zhuce: function(req, res) {
        res.write("我是注册方法");
    }
}

注意,直接访问localhost:8000会报错,因为path是/,没有对应路由
需要访问**localhost:8000/login

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容