[英]Why am I not able to access the express server from a different file?
I have set up an express server as follows (inside of server.js
):我已经如下设置了一个快速服务器(在
server.js
内部):
const app = express();
.........
.....
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Server started on port ${PORT}`)
);
module.exports = server;
Inside of another file socket.js
:在另一个文件
socket.js
内部:
const server = require("./server");
const socketio = require("socket.io");
const io = socketio(server);
io.on("connection", function (socket) {
console.log("A user just joined!");
socket.on("disconnect", () => {
console.log("A socket just left!");
});
});
For some reason I get an error in my console while trying to connect to the socketio on the client:出于某种原因,在尝试连接到客户端上的 socketio 时,我的控制台出现错误:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N8-d7Q4 404 (Not Found)
The error does not occur if I execute everything in a single file (without exporting the server):如果我在单个文件中执行所有内容(不导出服务器),则不会发生错误:
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Server started on port ${PORT}`)
);
const socketio = require("socket.io");
const io = socketio(server);
io.on("connection", function (socket) {
console.log("A user just joined!");
socket.on("disconnect", () => {
console.log("A socket just left!");
});
});
I don't understand what's wrong.我不明白出了什么问题。 Does module.exports not work with the express server or is this is a socketio issue?
module.exports 是否不适用于快速服务器,或者这是 socketio 问题?
It appears you're not loading socket.js
at all.看来您根本没有加载
socket.js
。 When you had only the one file, you just did node app.js
and that would work fine.当您只有一个文件时,您只需执行
node app.js
即可。 But, if you do node app.js
with your two files, then there's nothing to ever load socket.js
at all.但是,如果你用你的两个文件做
node app.js
,那么根本就没有任何东西可以加载socket.js
。 In fact, the way you have the two files laid out, you would have to do:事实上,按照您布置这两个文件的方式,您必须这样做:
node socket.js
to initialize things.初始化事物。 Then,
socket.js
does a require('./app.js')
to get app.js loaded.然后,
socket.js
执行require('./app.js')
来加载 app.js。
I was wondering if it's impossible to module.exports = server at all
我想知道是否根本不可能 module.exports = server
Yes, you can freely export the server and you are exporting it.是的,您可以自由地导出服务器并且正在导出它。
Another way of doing things is to still have app.js
be your main file that you load to start up your app and you load socket.js
from there and pass it the server
object so it can use it.另一种做事的方法是仍然让
app.js
作为您加载以启动应用程序的主文件,然后从那里加载socket.js
并将其传递给server
object 以便它可以使用它。
// app.js
const server = const server = app.listen(...);
// load socket.js and pass it our server
require('./socket.js')(server);
Then in socket.js:然后在 socket.js 中:
// socket.js
const socketio = require("socket.io");
module.exports = function(server) {
const io = socketio(server);
// rest of your module code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.