【问题标题】:How to add static file to http server? [duplicate]如何将静态文件添加到http服务器? [复制]
【发布时间】:2017-11-12 23:32:24
【问题描述】:

我想通过 node.js 实现一个聊天室。

我使用socket.io提供的模板。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');

app.get('/', function(req, res) {
    fs.readFile(__dirname + '/style.css');    // I don't know how to import the style.css to the chat.html
    // fs.readFile(__dirname + '/images/');   // And how to add images file to the server
    res.sendFile(__dirname + '/chat.html');
});

io.on('connection', function(socket) {
    console.log('a user connected');
    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
    socket.on('chat message', function(msg) {
        console.log('message: ' + msg);
    })
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
    });
    socket.broadcast.emit('hi');
});


http.listen(8888, function() {
    console.log('listening on *:8888');
});

当我输入时

node index.js

在终端中,它会显示出来

listening on *:8888
(node:12873) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

现在,服务器可以工作了,但格式已经消失了。

我不知道如何纠正这个问题。我希望 chat.html 可以是 style.css 指定的格式,并且消息可以以我想要的格式(也由 style.css 指定)发送,而不仅仅是纯文本。

【问题讨论】:

标签: javascript html node.js express


【解决方案1】:

您必须告诉节点您计划用于“静态文件”的目录。

你就这样

const staticCont = express.static(__dirname + "/public");

其中“public”是存放静态内容(如 CSS 或前端 JS 文件等)的文件夹的名称。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    相关资源
    最近更新 更多