gpt4 book ai didi

javascript - NodeJS 引用错误 : io is not defined

转载 作者:行者123 更新时间:2023-11-29 22:04:13 24 4
gpt4 key购买 nike

我开始使用 node JS,遇到 io lib 问题,这里是错误:

ReferenceError: io is not defined
at exports.index (D:\dev\lib\index.js:9:5)
at callbacks (D:\dev\node_modules\express\lib\router\index.js:164:37)
at param (D:\dev\node_modules\express\lib\router\index.js:138:11)
at pass (D:\dev\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (D:\dev\node_modules\express\lib\router\index.js:1 73:5)
at Object.router (D:\dev\node_modules\express\lib\router\index.js:33:1 0)
at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.methodOverride [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:49:5)
at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.urlencoded [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:51:37)

这是我的 app.js 文件的内容:

var express = require('express'); 
var path = require('path');

var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
fs = require('fs');

app.set('port', process.env.PORT || 8080); app.set('views',
path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon()); app.use(express.logger('dev'));
app.use(express.json()); app.use(express.urlencoded());
app.use(express.methodOverride()); app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', require('./lib').index);

server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

我的文件 lib/index.js :

exports.index = function(req, res){
res.render('index');
io.sockets.on('connection', function (socket) {
socket.emit('message', 'welcome');
});
};

谁能帮帮我?

最佳答案

您需要将 io 传递给您的路线:

exports.index = function(io) {
return function(req,res) {
res.render('index');
io.sockets.on('connection', function (socket) {
socket.emit('message', 'welcome');
}
}
}

然后在app.get中调用它作为一个函数:

app.get('/', require('./lib').index(io));

我建议用您的其他变量声明 require('./lib') 部分。这将允许代码重用和更好的可读性(与每个人相关)。

var /*other variables*/,
lib = require('./lib');

然后你可以做 app.get('/', lib.index(io));

只是一个想法。

关于javascript - NodeJS 引用错误 : io is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com