Node.js中createServer内console.log刷新页面输出两次的原因解析
console.log Runs Twice on Page Refresh Hey there! I’ve run into this exact quirk before—let’s break down what’s happening and how to fix it.
The Root Cause
That double console.log is all down to a default browser behavior. When you load a page in your browser, it sends two separate requests to your server:
- The main request for your actual page (e.g.,
http://localhost:3000/) - A secondary request to fetch the site’s favicon (
/favicon.ico)—this is the tiny icon that shows up in your browser tab, and browsers automatically request it without you explicitly asking.
Since your server’s callback function runs for every incoming request, both the root path request and the favicon request trigger that console.log("ksdguf") line.
To confirm this, add a quick log of the request URL to your code:
console.log("Incoming request for:", request.url);
When you refresh, you’ll see two lines in your terminal: one for / and one for /favicon.ico.
How to Fix It
If you want your log (and main page logic) to only run once per page load, add a check for the request URL in your server callback. Here’s a modified version of your code:
var http = require('http'); var server = http.createServer(function(request, response) { // Only run your main logic for the root path request if (request.url === '/') { response.writeHead(200, { "content-type": "text/html" }); response.write("<h1>Welcome to Node server</h1>"); console.log("ksdguf"); // This will now only run once per refresh response.end(); } else { // Handle other requests (like favicon) with a 404 or empty response response.writeHead(404); response.end(); } }); server.listen(3000); console.log("Server started, Access it using browser");
If you want to serve a proper favicon instead of returning a 404, you can use the fs module to read and return an icon file—but for just stopping the double log, the URL check is a simple and effective fix.
内容的提问来源于stack exchange,提问作者Anshuman Upadhyay

