node学习之路由

//luyou.js
var http=require("http")
var url=require("url")
var obj=require("./comm")

http.createServer((req,res)=>{
	
	res.writeHead(200,{'content-type':'text/html;charset=utf-8'})
	if(req.url!="/favicon.ico"){
       //去除路径前面的斜杠/
       //路由--获取path路径url.parse(req.url).pathname.replace(/\//,‘’)
		var path = url.parse(req.url).pathname.replace(/\//,'');
		console.log(path)
		

        //try{   路径存在  }catch(e){    路径不存在  (重定向)}
		try{
                  //请求路径不同,根据obj中的路由配置去返回不同的数据
			obj[path](req,res)
		}catch(e){
             //当没有的时候返回index路由的配置
			obj["index"](req,res)
		}
		
	}
		
}).listen(3000)
//comm.js
var fs = require("fs")
const https = require('https');

var obj={
	
	"index":function(req,res){
		res.write("<h1>首页</h1>");
		res.end();
	},
	"about":function(req,res){
		res.write("<h1>关于</h1>");
		res.end();
	},
	"other":function(req,res){
		res.write("<h1>其他</h1>");
		res.end();
	},
	"data":function(req,res){
		fs.readFile("./data.json",(err,data)=>{
//			data.map(function(item){
//				res.write('item.name');
//			})
			res.write(data);
			res.end()
		})
	},
	"demo2":function(req,res){
		fs.readFile("./demo2.html",(err,data)=>{
			res.write(data);
			res.end()
		})
	},
	"douban":function(reqq,ress){
		  const options = {
		  hostname: 'api.douban.com',
		  port: 443,
		  path: '/v2/movie/in_theaters',
		  method: 'GET'
		};
		
		var str = "";
		var arr = [];
		//开始请求
		const req = https.request(options, (res) => {
		
			  res.on('data', (d) => {
			    str +=d;
			  });
			  
			  res.on('end',()=>{
			  	var list=JSON.parse(str).subjects
					list.map(function(item){
						arr.push(item.title)
					})	
					
					ress.write(JSON.stringify(arr))
				  	ress.end()
			  })
		});
		//请求错误
		req.on('error', (e) => {
		   console.error(e);
		});
		
		//结束请求
		req.end();
	}
	
	
}

module.exports = obj;
//data.json
[{
	"name":"小明",
	"age":"22"
},
{
	"name":"小兰",
	"age":"20"
},
{
	"name":"小红",
	"age":"18"
}
]
//demo2.html
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<a href="/index">首页</a>
		<a href="/about">关于</a>
		<a href="/other">其他</a>
	</body>
</html>

路由:实现单页面应用的
            
            singlepage 单页面应用(SPA)
            
            前端路由:用来根据不同的URL地址(path路径)展示不同的视图内容
            后端路由:根据不同的URL地址(path路径)展示不同的数据,形成接口

猜你喜欢

转载自blog.csdn.net/keep789/article/details/81490057