Node入门--11-->Route

  • What:当前地址路径下又拼接的内容,显示不同的页面
  • How:

  1.编辑文件index.html,contact.html以及Api文件夹下的user.html

  

  2.app.js文件

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('index.html', 'utf8').pipe(res);
        }else if(req.url === '/contact'){
            res.writeHead(200,{"Content-type":"text/html"});
            fs.createReadStream('contact.html', 'utf8').pipe(res);
        }else if (req.url === '/Api/user'){
            var data = [{name:"Jona",age:21}, {name:"Daneil",age:25}];
            res.writeHead(200,{"Content-type":"application/json"});
            res.end(JSON.stringify(data));//展示JSON数据
        }
    }
});
server.listen(3033,'127.0.0.1');
console.log("OK");

  3.在页面中打开

  http://127.0.0.1:3033/Api/user,根据3033后的文件名不同,展示不同的画面

  

posted @ 2017-06-01 16:09  female攻城狮  阅读(161)  评论(0编辑  收藏  举报