node小记

写点小心情吧,好久不写博客了,终于在朋友的鼓励与刺激下强迫自己更了一篇,写之前万分难受,但是准备好材料之后感觉还是不错哒,以后每个月最少一篇,多则不限。

概要

介绍

主要关于node的路由与接口之间的关系

node如何写接口

//app.js
var http = require("http");
var fs = require("fs");
var url = require('url');
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
if(pathname == '/'){
var readable = fs.createReadStream("./public/index.html")
response.writeHead(200, {"Content-Type": "text/html"});
readable.pipe(response);
}else if(pathname == '/postData'){
var data = {"username":"Book","pwd":"111111"}; 
data = JSON.stringify(data); 
var opt = { 
host:"localhost", 
port:'9001', 
method:'POST', 
path:'/test', 
headers:{ 
"Content-Type": 'application/json', 
"Content-Length": data.length 
} 
} 
var body = ''; 
var req = http.request(opt, function(res) { 
console.log("response: " + res.statusCode); 
res.on('data',function(data){ 
body += data;
}).on('end', function(){ 
console.log(body,'body');
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(body);
response.end();
}); 
})
.on('error', function(e) { 
console.log("error: " + e.message); 
}) 
req.write(data); 
req.end(); 
}else if(pathname == '/test'){
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("testword");
response.end();
}else if(pathname == '/world'){
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("world");
response.end();
}
}).listen(9001);
console.log('Server running!');


//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>test</title>
</head>
<body>
<div class="click">click</div>
<div class="click1">click1</div>
</body>
<script src="//cdn.bootcss.com/jquery/2.2.1/jquery.js"></script>
<script type="text/javascript">
$(".click").on('click',function(){
$.ajax({
type: 'GET',
url: '/test',
dataType: 'json',
data: {
"book":"shuben"
},
success: function(data,res){

},
});
})
$(".click1").on('click',function(){
$.ajax({
type: 'POST',
url: '/postData',
dataType: 'json',
data: {
book:"shuben"
},
success: function(data,res){

},
});
})

</script>
</html>
  1. 如果浏览器直接访问http://localhost:9001会读取./public/index.html的内容
  • 点击页面中的click,会去请求http://localhost:9001/world这个接口,node会抓到这个请求,在接口里返回testword,就是我们平时在network中看到的preview里面的数据,但是页面依然是./public/index.html的内容,这个相当于以ajax的形式去调取接口
  • 点击页面中的click1,会去请求http://localhost:9001/postData这个接口,在这个接口中,node会继续去访问了http://localhost:9001/test这个接口,最后会将http://localhost:9001/test返回的内容testword作为http://localhost:9001/postData接口返回的内容,但这个过程浏览器不会看到,这就是后端解决跨域的方式
  1. 如果浏览器直接访问http://localhost:9001/test,页面会展示testword
  2. 如果浏览器直接访问http://localhost:9001/postData,页面会展示testword,和上面同理
  3. 对于前端,刚刚接触node,会有一个特别大的误区,就是对于接口和url总分不清,对于node来说,url也是接口,和ajax请求的接口是一样的意思,其实对于我们平时看到的所有url,都可以作为接口访问,这也是爬虫的原理

node基础模块(之后会有对应的篇幅)

  • buffer
  • event
  • file
  • stream

posted on 2017-06-06 14:49  bless-19946  阅读(263)  评论(0编辑  收藏  举报

导航