如何在Node.js中加载CSS文件?本地CSS文件404问题求助
问题分析与解决建议
首先咱们来拆解问题:你的Node.js服务器目前只处理了根路径/的请求,当浏览器尝试加载/css/intro.css时,服务器没有对应的处理逻辑,直接返回404错误——这就是你在Network标签里看到的状态。另外,home.html里的CSS路径也有问题,导致请求的目标路径不对。
下面是具体的修复步骤:
1. 修正home.html中的CSS路径
因为home.html的内容是被嵌入到根路径/的页面中的,相对路径../css/intro.css会指向错误的位置。把它改成绝对路径:
<link rel="stylesheet" href="/css/intro.css" type="text/css" >
2. 在服务器代码中添加静态资源(CSS)的处理逻辑
修改你的main.js,在处理根路径之前先处理CSS文件的请求,确保服务器能正确读取并返回CSS内容:
var http = require('http'); var fs = require('fs'); var url = require('url'); var path = require('path'); // 移到顶部,避免重复加载模块 function templateHTML(description, queryDataid){ var _template=` <!doctype html> <html> <head> <meta charset="utf-8"> <title>11</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.css"> </head> <body> ${description} </body> </html> `; return _template; } var app = http.createServer(function(request, response){ var _url = request.url; var queryData = url.parse(_url, true).query; // 解开注释,否则queryData.id会报错 var pathname = url.parse(_url, true).pathname; console.log("1. "+pathname); console.log("2. "+(queryData.id || 'undefined')); // 避免id不存在时控制台报错 // 优先处理CSS静态资源请求 if (pathname.startsWith('/css/')) { // 构建完整的文件路径,__dirname是当前脚本所在的项目根目录(nodejsExample) var cssFilePath = path.join(__dirname, pathname); fs.readFile(cssFilePath, 'utf-8', function(err, cssContent) { if (err) { // 文件不存在时返回明确的404提示 response.writeHead(404, {'Content-Type': 'text/plain'}); response.end('CSS file not found'); return; } // 设置正确的Content-Type,让浏览器识别为CSS文件 response.writeHead(200, {'Content-Type': 'text/css'}); response.end(cssContent); }); return; // 处理完CSS请求后直接返回,不执行后续逻辑 } // 原有的根路径处理逻辑 if(pathname === '/'){ if(queryData.id === undefined){ var title = 'Welcome to esseltree'; var description = fs.readFileSync("home.html","utf-8"); var template = templateHTML(description, queryData.id); response.writeHead(200, {'Content-Type': 'text/html'}); response.end(template); } else{ var title = queryData.id; fs.readFile(`html/${queryData.id}`, 'utf-8', function(err, description){ if (err) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.end('Page not found'); return; } var template = templateHTML(description, queryData.id); response.writeHead(200, {'Content-Type': 'text/html'}); response.end(template); }); } } else{ response.writeHead(404, {'Content-Type': 'text/plain'}); response.end('Page not found.....'); } }); app.listen(80);
额外优化说明
- 把
path模块的require移到顶部,避免每次请求都重复加载模块,更符合Node.js开发规范。 - 给所有响应都添加了
Content-Type头,让浏览器能正确解析返回的内容类型。 - 增加了错误处理逻辑,比如文件不存在时返回明确的提示,避免服务器因为未捕获的异常崩溃。
- 修正了控制台打印
queryData.id的潜在报错问题,当id不存在时会显示undefined而不是抛出错误。
现在重启你的Node.js服务器,再访问页面,应该就能正常加载intro.css了。
内容的提问来源于stack exchange,提问作者Yoonjong Lee
相关产品推荐
相关产品推荐

