为什么我的节点服务器处理请求两次?
我有以下简单的节点服务器。
const http = require('http'); http.createServer(function(req, resp) { console.log("request arrived.") resp.writeHead(200, { 'Content-Type': 'application/json' }); resp.end("Hello world!!"); }).listen(3000);
每当我用url http://localhost:3000/
来打这个请求的时候,它打印两次request arrived
消息。
我不知道,究竟是什么原因呢。 请一些人解释一下。
我附上了截图。
浏览器很可能正在请求favicon.ico
文件。 您可以通过打印URL来确认,如下所示
console.log("request arrived for URL", req.url);
当我在我的机器上用Chrome浏览器尝试这个时,我得到了
request arrived for URL / request arrived for URL /favicon.ico
如果你想避免这一点,那么你需要专门处理favicon
请求。 大概,你可以做这样的事情,如图所示
if (req.url === '/favicon.ico') { resp.writeHead(200, {'Content-Type': 'image/x-icon'} ); resp.end(); console.log('favicon requested'); return; } console.log("request arrived.") resp.writeHead(200, { 'Content-Type': 'application/json' }); resp.end("Hello world!!");