如何在NodeJS服务器上部署两个可分别访问的HTML页面
Fixing Your Multi-Page Node.js Server Issue
Hey there! I get it—setting up a single-page server feels straightforward, but adding a second route can trip you up if you’re not parsing the request URL correctly. Let’s walk through fixing this step by step.
From your code snippet, it looks like you probably didn’t properly define or populate the page variable you referenced in your if statement. Let’s rewrite your server to reliably handle both /index and /about routes.
Working Server Code
const http = require("http"); const fs = require("fs"); const port = 3000; const server = http.createServer((request, response) => { // Parse the incoming request URL to extract the path const url = new URL(request.url, `http://localhost:${port}`); const requestedPath = url.pathname; // Route handling logic if (requestedPath === "/" || requestedPath === "/index") { // Serve the index.html file fs.readFile("./index.html", (err, data) => { if (err) { response.writeHead(404, { "Content-Type": "text/html" }); return response.end("<h1>404 - Index Page Not Found</h1>"); } response.writeHead(200, { "Content-Type": "text/html" }); response.write(data); return response.end(); }); } else if (requestedPath === "/about") { // Serve the about.html file fs.readFile("./about.html", (err, data) => { if (err) { response.writeHead(404, { "Content-Type": "text/html" }); return response.end("<h1>404 - About Page Not Found</h1>"); } response.writeHead(200, { "Content-Type": "text/html" }); response.write(data); return response.end(); }); } else { // Handle unknown routes with a 404 response.writeHead(404, { "Content-Type": "text/html" }); response.end("<h1>404 - Page Not Found</h1>"); } }); server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Key Fixes & Explanations
- URL Parsing: We use the modern
new URL()API to reliably extract the path from the request. This avoids issues with query parameters or malformed URLs that older parsing methods might struggle with. - Clear Route Checks: Explicit
if/elseblocks handle/index(plus the root/as a user-friendly bonus) and/aboutroutes, each loading the corresponding HTML file. - Error Handling: Added checks for file read errors (like if your HTML files are missing) to return proper 404 responses instead of crashing the server.
Quick Setup Tips
- Make sure your
index.htmlandabout.htmlfiles are in the same folder as your server script, or update the file paths infs.readFile()to match their actual location (e.g.,./public/index.htmlif they’re in apublicsubfolder). - Run the server with
node your-server-filename.js, then visit:http://localhost:3000/indexorhttp://localhost:3000/for your index pagehttp://localhost:3000/aboutfor your about page
This should resolve the issue you were having with adding the second page. If you hit any other snags, feel free to ask!
内容的提问来源于stack exchange,提问作者Charlote22
相关产品推荐
相关产品推荐

