如何使用Node.js服务器加载本地HTML与CSS静态资源文件
你遇到的CSS无法加载的问题,本质是原生http模块没有自动处理静态资源请求的逻辑,要么是收到CSS请求时返回了错误内容,要么是响应头的Content-Type设置错误,导致浏览器无法识别为CSS文件。
你可以直接替换原有服务代码为以下版本即可实现HTML、CSS等静态资源的正常加载:
const http = require('http'); const fs = require('fs'); const path = require('path'); // 配置不同静态文件后缀对应的响应头类型 const mimeTypes = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg' }; let app = http.createServer((req, res) => { // 根路径默认返回index.html let filePath = req.url === '/' ? './index.html' : '.' + req.url; // 获取请求文件的后缀 const extname = String(path.extname(filePath)).toLowerCase(); const contentType = mimeTypes[extname] || 'application/octet-stream'; // 读取对应本地文件返回 fs.readFile(filePath, (error, content) => { if (error) { res.writeHead(404); res.end('404 Not Found'); } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf-8'); } }); }); app.listen(3000, '127.0.0.1'); console.log('Node server running on port 3000');
使用说明:
- 将你的
index.html和style.css放在和server.js相同的目录下 - 在
index.html的<head>标签内添加CSS引入代码:<link rel="stylesheet" href="style.css"> - 重启Node服务后访问
http://127.0.0.1:3000即可正常加载带样式的页面
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

