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

Node服务器CSS加载失败排查(含switch语句实现代码)

问题描述

启动Node服务器后出现CSS文件加载异常:本地用live server时CSS可正常运行,但自建服务器仅能加载除CSS外的其他资源。请求URL为/public/CSS/style.css,文件状态码为200,响应头为undefined。

后端代码如下:

const express = require('express');
const path = require('path');
const cors = require('cors');
const fs = require('fs');
const http = require('http');
const url = require('url');
const { extname } = require('path');
const app = express();
const figlet = require('figlet');
const { connect } = require('tls');
const exp = require('constants');
const PORT = process.env.PORT || 8000

app.use(cors());


let server = http.createServer((req, res) => {

    // Creates File Path
    let filePath = path.join(
        __dirname,
        'public',
        req.url === '/' ? 'index.html' : req.url
    );

    console.log(filePath)


    // Gets Extension from a file
    let extname = path.extname(filePath);

    console.log(extname)

    // Default Content Type
    let contentType = 'text/html';



    switch (extname) {

        case '.css':
            contentType = 'text/css';
            break;

        case '.js':
            contentType = 'text/javascript';
            break;

        case '.json':
            contentType = 'application/json';
            break;

        case '.jpeg':
            contentType = 'image/jpeg';
            break;

        case '.jpg':
            contentType = 'image/jpg';
            break;

        case '.png':
            contentType = 'image/png';
            break;

        case '.webp':
            contentType = 'image/webp';
            break;
    }

    // Read File

    fs.readFile(filePath, (err, content) => {

        // If ENONENT Error is returned
        if (err) {
            if (err.code === 'ENOENT') {
                figlet('Page Not Found!!', (error, data) => {
                    if (error) {
                        console.log('Something went wrong');
                        console.dir(error)
                        return
                    }
                    res.end(data, 'utf8')
                })
            }
            else {
                // Some Other Error
                console.log(err.code)
                res.writeHead(500);
                res.end(`Server Error: ${err.code}`);
            }
        } else {
            // Success
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(content, 'utf8');
        }
    });

});


server.listen(PORT, () => {
    console.log(`The Server is running on port: ${PORT}`)
})
问题原因与解决方案

核心问题

  1. 路径错误:当请求URL为/public/CSS/style.css时,代码生成的文件路径是__dirname/public/public/CSS/style.css(req.url被直接拼接到public目录后),但实际CSS文件应该在__dirname/public/CSS/style.css,导致读取的是不存在的文件。
  2. 手动处理静态资源的冗余风险:引入了Express却未使用其静态资源中间件,手动实现HTTP服务器容易出现路径、响应头处理等细节错误。

修复方案(推荐Express标准做法)

直接用Express的express.static中间件托管静态资源,这是处理静态文件的标准方式,无需手动拼接路径和处理响应:

const express = require('express');
const path = require('path');
const cors = require('cors');
const PORT = process.env.PORT || 8000

const app = express();

app.use(cors());
// 托管public目录下的静态资源,访问时无需加/public前缀
app.use(express.static(path.join(__dirname, 'public')));

// 处理根路径请求
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(PORT, () => {
    console.log(`服务器运行在端口: ${PORT}`);
});

配套调整

修改HTML中CSS的引用路径:将/public/CSS/style.css改为/CSS/style.css,因为express.static已将public设为静态资源根目录。

若坚持手动处理HTTP服务器的修复方式

如果一定要保留手动实现的HTTP服务器,需要修正路径拼接逻辑,去掉请求URL中的/public前缀:

// 修改filePath生成逻辑
let filePath;
if (req.url === '/') {
    filePath = path.join(__dirname, 'public', 'index.html');
} else if (req.url.startsWith('/public/')) {
    // 去掉/public前缀,直接拼接对应路径
    filePath = path.join(__dirname, req.url);
} else {
    filePath = path.join(__dirname, 'public', req.url);
}

同时确保HTML中CSS的引用路径与实际文件结构匹配。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:45:43