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路径)展示不同的数据,形成接口

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值