簡體   English   中英

為什么我不能在 Socket.io http 服務器上使用 express.js 獲取方法

[英]Why I cannot use express.js get method with Socket.io http server

這是我的代碼:

const consts        = require('./public/script/consts.js');
const express       = require('express');
const app           = express();
const server        = require('http').createServer(app);
const { Server }    = require('socket.io');
const io            = new Server(server);

function io_on_connection(socket) {
    console.log("a user connected"); // TODO: Emit user connected
    
    socket.on('sendmessage', (message) => {
        io.emit("recievemessage", { username: "litte_coder", message: message });
    });
}

function app_get_root(req, res) {
    console.log("index");
    res.sendFile(__dirname + '/public/index.html');
}

function server_listen() {
    console.log('Server is running...');
}

/* Socket.io */
io.on('connection', io_on_connection);

//app.use(express.static(__dirname + '/public'));
app.get('/', app_get_root);

server.listen(consts.PORT, server_listen);

當我使用app.use(express.static...)時, app_get_root回調不會調用,但我的 index.html 已經服務。 我的目錄結構是這樣的:

├── app.js
├── package.json
├── package-lock.json
└── public
    ├── index.html
    ├── script
    │   ├── consts.js
    │   └── index.js
    └── style
        └── style.css

但是,如果我的 app_get_root 回調不起作用,它如何為我的 index.html 文件提供服務?

我已經運行了它,如果它對我有用,甚至添加 app.use(express.static("public"));

你怎么知道 app_get_root 沒有被調用。

console.log("index") 它在節點控制台中打印,而不是在瀏覽器中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM