02 路由

2018-10-18  本文已影响0人  亨锅锅

题记:编程没有捷径,你敲坏多少键盘,就有多大出息
敢问路在何方,路在脚下。。。

路由就是你访问不同的资源,得到不同的响应内容
1 创建contact.html文件,api文件夹,api文件夹下创建docs.html文件
来看下面的代码

// 通过 http 模块,创建本地服务器
var http = require('http');
var fs = require('fs');

// 创建服务器方法
var server = http.createServer(function (req,res) {

    if(req.url !== '/favicon.ico'){

        if(req.url === '/home' || req.url === '/'){
            res.writeHead(200,{"Content-type":"text/html"});
            fs.createReadStream(__dirname + '/index.html','utf8').pipe(res);
        }else if (req.url === '/contact'){
            res.writeHead(200,{"Content-type":"text/html"});
            fs.createReadStream(__dirname + '/contact.html','utf8').pipe(res);
        }else if(req.url === '/api/docs'){
            res.writeHead(200,{"Content-type":"text/html"});
            fs.createReadStream(__dirname + '/api/docs.html','utf8').pipe(res);
        }else if(req.url === '/getJson'){
            var json = [{"name":"heng","age":18},{"name":"bob","age":11}];
            res.writeHead(200,{"Content-type":"application/json"});
            res.end(JSON.stringify(json));
        }else{
            res.writeHead(200,{"Content-type":"text/plain"});
            res.end('404 not found');
        }
    }
});

// 服务对象 监听服务器地址以及端口号
server.listen(8888,"127.0.0.1");

console.log('server is running');

分别访问
http://127.0.0.1:8888
http://127.0.0.1:8888/home
http://127.0.0.1:8888/contact
http://127.0.0.1:8888/api/docs
http://127.0.0.1:8888/getJson
http://127.0.0.1:8888/xxx
看看得到什么结果?

上一篇 下一篇

猜你喜欢

热点阅读