Node.js 路由初步

一、什么是路由?

URL :   http://localhost:8000/login   ===> login就是路由

应用:

        首先拿到URL ,然后在server.js里面解析,用正则表达式,把根目录下边的类似login 还是其他的,要访问的字符串拿到;访问一个路由的js文件,通过这个传入的字符串去访问对应的方法。

截取字符串,到路由中找到相应的方法,进行读取,拿到相应的HTML文件,再把HTML的内容显示到页面上。

二、应用

1、怎么拿到URL?

①、新建


②、内容
var    http    =    require('http');
//node.js 自带的
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"){
				//拿到URL
                var pathname = url.parse(request.url).pathname;
				//正则
				pathname = pathname.replace(/\//, '');//替换掉前面的/ ,变成空字符串
				console.log(pathname);
                response.end('');
        }
}).listen(8000);
console.log('Server    running    at    http://127.0.0.1:8000/');  
③、运行


④、不加 pathname = pathname.replace(/\//, '');//替换掉前面的/ ,变成空字符串 之前运行出来的是:


当然,你也可以把login 换成是其他的单词也是可以的!!

三、从URL中获取路由信息 ,通过路由字符串调用对应的函数

1、新建luyou


2、内容
//声明函数集
module.exports={
    login:function(req,res){
        res.write("我是login方法");
    },
    setin:function(req,res){
        res.write("我是注册方法");
    }
}
3、在n4中添加信息
var    http    =    require('http');
//node.js 自带的
var    url    =    require('url');
//获取luyou.js
var    luyou    =    require('./luyou');
http.createServer(function    (request,    response)    {
        response.writeHead(200,    {'Content-Type':    'text/html;    charset=utf-8'});
        if(request.url!=="/favicon.ico"){
				//拿到URL
                var pathname = url.parse(request.url).pathname;
				//正则
				pathname = pathname.replace(/\//, '');//替换掉前面的/ ,变成空字符串
				console.log(pathname);
				luyou[pathname](request,response);
                response.end('');
        }
}).listen(8000);
console.log('Server    running    at    http://127.0.0.1:8000/');  
4、运行

我先运行了login,然后运行的setin,不是运行一个出来两个结果!!



猜你喜欢

转载自blog.csdn.net/qq_28289405/article/details/80605885