赞
踩
自己写了一个简单的路由,但是发现总是出错,最后用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
*/
删除注释就可阻止服务器对图标请求的相应。
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。