node.js 学习四 之 路由

2016-12-25  本文已影响20人  skuare520

路由就是根据浏览器的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

上一篇 下一篇

猜你喜欢

热点阅读