《Node.js实战(第二版)》第30页回调示例运行异常求助
Troubleshooting Your Unresponsive localhost:8000 for blog_recent.js
Hey there, I’ve been in your shoes working through Node.js books—let’s walk through common issues that could cause your blog_recent.js to not respond when you hit localhost:8000:
Check if the server actually started successfully
After runningnode .\blog_recent.js, take a close look at your terminal. Do you see a confirmation message like "Server running on http://localhost:8000"? If not, your script might have exited silently due to a syntax error, missing dependency, or file path issue. Scan the terminal for any error messages (likeReferenceErrorfor undefined variables, orError: ENOENTfor missing files) and fix those first.Verify your server’s response logic
Double-check the code from page 30 to confirm two key things:- You’re properly creating an HTTP server with
http.createServer() - The request handler callback actually sends a response to the client. If you forget
res.end()or skip writing content withres.write()before ending the response, the browser will hang indefinitely waiting for a response that never comes. For example, if your code reads the JSON file but fails to pass that data into the response, you’ll get nothing in the browser.
- You’re properly creating an HTTP server with
Check for port conflicts
Another common culprit is another program already using port 8000. On Windows, run this command in Command Prompt to check:netstat -ano | findstr :8000If you see a PID listed, a process is occupying the port. You can either kill that process via Task Manager (using the PID) or change the port number in your
blog_recent.jscode (e.g., switch to 3000) and restart the server.Validate your JSON file path and content
Make sure the JSON file your script is trying to read exists in the correct directory (same folder asblog_recent.js, unless you specified an absolute path). Also, confirm the JSON is valid—even a missing comma or mismatched quote will causeJSON.parse()to throw an error, which might crash your server or prevent it from generating a response. Add aconsole.log()after reading the JSON to confirm you’re getting the expected data.Rule out browser/network quirks
Sometimes browsers cache failed requests, so try openinglocalhost:8000in an incognito window or pressCtrl+F5to force a hard refresh. Also, ensure your local firewall isn’t blocking incoming connections to port 8000.
内容的提问来源于stack exchange,提问作者KamRon

