UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function
Posted
技术标签:
【中文标题】UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function【英文标题】: 【发布时间】:2021-01-21 00:29:03 【问题描述】:我正在使用 Socket.io 进行实时图像上传过程,但我收到了下面提到的这个错误。我通过引用 answer 在不同的文件中编写套接字和 app.js 逻辑现在我想在控制器文件中发出该套接字事件但得到了错误
下面是我的代码
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const indexRouter = require("./routes/index");
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var sockets = require('./apis/socket.io');
// configuration ===========================================
var port = config.PORT || 8081; // set our port
sockets.getSocketIo(http);
app.use(bodyParser.json( limit: '50mb' ));
app.use(bodyParser.urlencoded(
limit: '50mb',
extended: true,
parameterLimit: 50000
));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res)
res.sendFile(__dirname + '/index.html');
);
http.listen(port, () =>
console.log('Magic happens on port ' + port); // shoutout to the user
);
exports = module.exports = app;
这是socket.io.js
文件代码
var socketio = require('socket.io');
var io = ;
module.exports =
getSocketIo: function (app)
let userId = 1
io = socketio.listen(app);
io.sockets.on('connection', function (socket)
console.log("new connection: " + socket.id);
console.log(socket)
console.log('socket connected')
// let rooms = socket.id
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" +
userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
io.sockets.in(userId).emit('Image_upload', "Image uploading is started");
console.log(socket.room)
console.log(socket)
);
;
这是api控制器的控制器代码
report_data: async (req, res) =>
if (!req.body.id)
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS)
io.emit('progress', "Image is Uploading started Please Wait A minute");
io.emit('error', "clients connected!");
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/$Id`;
req.body.data_url = path
sequelize.sequelize.transaction(async (t1) =>
let result = error.OK
result.data = data
logger.info(result);
return res.status(200).send(result)
).catch(function (err)
logger.warn(err);
console.log(err)
return res.status(500).send(error.SERVER_ERROR)
)
,
【问题讨论】:
【参考方案1】:您可以在文件中进行如下更改
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
const indexRouter = require("./routes/index");
// configuration ===========================================
var port = config.PORT || 8081; // set our port
app.use(bodyParser.json( limit: '50mb' ));
app.use(bodyParser.urlencoded(
limit: '50mb',
extended: true,
parameterLimit: 50000
));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res)
res.sendFile(__dirname + '/index.html');
);
http.listen(port, () =>
console.log('Magic happens on port ' + port); // shoutout to the user
);
app.locals.io = io
exports = module.exports = app;
socket.io.js
let io;
const getSocketIo = (http) =>
let userId = 1
io = require('socket.io')(http);
io.sockets.on('connection', function (socket)
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
console.log("new connection: " + socket.id);
console.log('socket connected')
);
module.exports =
getSocketIo,
io
;
在你的控制器中,在你提到的 api 中添加这段代码,每当你想使用套接字时,在使用它之前添加这段代码
const io = req.app.locals.io;
【讨论】:
以上是关于UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function的主要内容,如果未能解决你的问题,请参考以下文章
[Unhandled promise rejection: TypeError: null is not an object (evaluating '_reactNativeImageCropPic