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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章