node 阻止favicon.ico请求

自己写了一个简单的路由,但是发现总是出错,最后用node-inspector调试才发现,浏览器每次发送一个GET请求,默认都会多发送一个图标请求。先贴上代码:

var http = require('http');
http.createServer(function(req,res) {
  console.log('hello world' + req.url);
  //if(req.url === /favicon.ico) return;//阻止响应
  res.writeHead(200,{'Content-Type':'text/plain'});
  res.end('Hello world\n');
}).listen(1337,'127.0.0.1');
console.log('Sever running at http://127.0.0.1:1337/');
/* 控制台输出
$ node hello-world.js
Sever running at http://127.0.0.1:1337/
hello world. req.url = /
hello world. req.url = /favicon.ico
*/

删除注释就可阻止服务器对图标请求的相应。

页面相当于刷新了两次,这也是我自己写的路由出错的原因。第一次快速渲染出来hello world,肉眼无法察觉,之后图标请求就出现路由出错,渲染出error 404 not found.’,代码如下:

var http = require('http')
  , url =require('url');
  var handle = function (req,res) {
      res.writeHead(200);
      res.end('Hello world.');

    };
  var handle404 = function (req,res) {
      res.writeHead(200);
      res.end('error 404 not found.');
    };
var routes = [];//储存路由
var use = function (path, action) {//请求路径,处理方法添加到路由中
  routes.push([path,action]);
};

use('/user/setting', handle);

http.createServer(function(req,res) {
  var pathname = url.parse(req.url).pathname;
  if (pathname === '/favicon.ico') return;
  for (var i = 0; i <routes.length; i++) {
    var route = routes[i];
    if(pathname === route[0]) {
      var action = route[1];
      action(req,res);
      return;
    }
  }
  handle404(req,res);
}).listen(1337,'127.0.0.1');
console.log('Sever running at http://127.0.0.1:1337/');

访问 http: //127.0.0.1:1337/user/setting之外的路径404错误

如何使用自己的图标?可参考:http://stackoverflow.com/questions/15463199/how-to-set-custom-favicon-in-node-js-express
中间件:https://github.com/expressjs/serve-favicon
维基百科Favicon介绍:https://en.wikipedia.org/wiki/Favicon

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值