用nodejs搭建最简单的http服务器,代码如下:
var http=require('http'); var url=require('url'); var i=0; http.createServer(function(req,res){ // console.log(url.parse(req.url)); res.end(''+i); console.log(i); i++; }).listen(3000); 打开浏览器,刷新一次,可以看见运行了两次,每次刷新输出的i比上次多2. 去掉注释代码: var http=require('http'); var url=require('url'); var i=0; http.createServer(function(req,res){ console.log(url.parse(req.url)); res.end(''+i); console.log(i); i++; }).listen(3000); 再次打开浏览器,刷新,看到控制台的输出如下: { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?asd=ads&asdfa=adsf', query: 'asd=ads&asdfa=adsf', pathname: '/', path: '/?asd=ads&asdfa=adsf', href: '/?asd=ads&asdfa=adsf' } 0 { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/favicon.ico', path: '/favicon.ico', href: '/favicon.ico' } 1 可以看到,一次刷新确实运行了两次,因为浏览器默认一次会请求favicon.ico,如果这不符合我们的业务逻辑,就可以通过解析url,当请求ico时不做逻辑处理。 var http=require('http'); var url=require('url'); var i=0; http.createServer(function(req,res){ if(url.parse(req.url).path=='/favicon.ico') return; console.log(url.parse(req.url).path); res.end(''+i); console.log(i); i++; }).listen(3000); ———————————————— 版权声明:本文为CSDN博主「zbuger」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 详情见原文链接: 原文链接:https://blog.csdn.net/zbuger/article/details/46853249 |
|