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

Express+Socket.io聊天应用CSS文件无法加载求助

问题排查与解决方案

核心错误

你把静态资源中间件app.use(express.static())放在了app.get('/')的路由处理函数内部,这会导致只有当用户访问根路径时才会注册这个中间件,而浏览器请求CSS文件的请求是独立于根路径请求的,此时中间件还未被注册,自然无法处理CSS的请求。

修正步骤

  1. 将静态资源中间件移到路由外部:把app.use(express.static(path.join(__dirname,'css')))放在所有路由定义之前,确保所有请求(包括CSS、JS等静态资源请求)都能经过这个中间件处理。
  2. 确认文件结构与引用路径:确保你的项目结构符合以下格式:
    项目根目录/
    ├── server.js
    ├── index.html
    └── css/
        └── style.css (你的CSS文件)
    
    同时在index.html中正确引用CSS,路径应为:
    <link rel="stylesheet" href="/style.css">
    

修正后的完整server.js代码

const express = require('express');
const app = express();
const { Server } = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);
const port = 80;
const path = require('path');

// 静态资源中间件放在路由之前,确保所有请求都能被处理
app.use(express.static(path.join(__dirname,'css')));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    socket.on('new-user', name => {
        socket.broadcast.emit('user-connected',name);
    })
    socket.on('send name', (username) => {
        io.emit('send name', (username));
        console.log(username)
    });
    socket.on('send message', (chat) => {
        io.emit('send message', (chat));
        console.log(chat);
    });
    socket.on('send-chat-message', message => {
        socket.emit('chat-message',{ message: message, name: users[socket.id]})
        console.log(message);
    })
    socket.on('disconnect',(name) => {
        socket.emit('user-disconnected',name);
        console.log(name)
    })
});

server.listen(port, () => {
    console.log(`Server is listening at the https://localhost/`);
});

额外注意点

  • 当前代码中users[socket.id]会报错,因为未声明users变量,可在代码顶部添加const users = {};解决。
  • 如果CSS文件放在css的子文件夹中(比如css/styles/main.css),引用路径需改为/styles/main.css。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:32:39