You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯Node.js天气应用仅加载HTML,CSS无法生效求助

问题原因与解决方案

你的CSS无法生效的核心原因是:当前HTTP服务器只处理了根路径/的请求,没有处理HTML中引用的CSS等静态资源的请求。当浏览器加载完HTML后,会自动发起CSS文件的请求(比如/style.css),但你的服务器没有对应处理逻辑,导致这些请求返回404,CSS自然无法加载。

修复步骤与代码修改

1. 新增静态资源处理逻辑

在服务器的请求处理函数中,添加对CSS等静态资源的判断,根据请求路径读取本地文件,并设置正确的响应头。

2. 修改后的完整代码

const fs = require("fs");
const http = require("http");
const requests = require("requests");

const homeFile = fs.readFileSync('home.html', 'utf-8');

const replaceVal = (tempVal, orgVal) => {
    let temperature = tempVal.replace("{%tempVal%}", orgVal.main.temp);
    temperature = temperature.replace("{%minTemp%}", orgVal.main.temp_min);
    temperature = temperature.replace("{%maxTemp%}", orgVal.main.temp_max);
    temperature = temperature.replace("{%country%}", orgVal.sys.country);
    return temperature;
}

const server = http.createServer((req, res) => {
    // 处理根路径请求,返回渲染后的HTML
    if (req.url === '/') {
        requests('https://api.openweathermap.org/data/2.5/weather?q=Pune&appid=0bfd89f4982a2d416a4ac5d299d03f9e&units=metric')
            .on('data', function (chunk) {
                const objData = JSON.parse(chunk);
                const arr = [objData];
                const realTimeData = arr.map(val => replaceVal(homeFile, val)).join("");
                res.write(realTimeData);
            })
            .on('end', function (err) {
                if (err) return console.log('connection closed due to errors', err);
                res.end();
            });
    } 
    // 处理CSS文件请求(假设你的CSS文件名为style.css,放在根目录)
    else if (req.url === '/style.css') {
        res.writeHead(200, {'Content-Type': 'text/css'});
        fs.readFile('style.css', (err, data) => {
            if (err) {
                res.writeHead(404);
                res.write('CSS file not found');
                res.end();
                return;
            }
            res.write(data);
            res.end();
        });
    }
    // 处理其他未匹配的请求,返回404
    else {
        res.writeHead(404);
        res.write('Page not found');
        res.end();
    }
});

server.listen(8000, "127.0.0.1");

关键说明

  • 响应头设置:返回CSS时必须设置Content-Type: text/css,否则浏览器无法识别这是CSS文件,不会应用样式。
  • 静态资源路径匹配:如果你的CSS文件放在子目录(比如/css/style.css),需要对应修改req.url的判断条件,同时读取文件的路径也要对应调整。
  • 错误处理:添加了文件不存在的错误处理,避免服务器崩溃,同时给浏览器返回明确的错误信息。

额外优化建议

如果你的应用有多个静态资源(JS、图片等),可以封装一个通用的静态资源处理函数,避免重复代码。比如:

function serveStaticFile(res, filePath, contentType) {
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(404);
            res.write('File not found');
            res.end();
            return;
        }
        res.writeHead(200, {'Content-Type': contentType});
        res.write(data);
        res.end();
    });
}

然后在请求处理中调用:

else if (req.url === '/style.css') {
    serveStaticFile(res, 'style.css', 'text/css');
} else if (req.url === '/app.js') {
    serveStaticFile(res, 'app.js', 'application/javascript');
}

内容的提问来源于stack exchange,提问作者Akash Suklabaidya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:25:43