Socket.io与Express.js路由 [英] Socket.io with Express.js routes
问题描述
我正在将socketio与expressjs及其路由用作中间件.下面是我的代码.目前,我的设置不适用于当前方法.以下是我正在使用的代码段,但没有一个起作用.怎么做?
I am using socketio with expressjs with its routes as a middleware. Below is my code. Currently, my setup is not working with my current approach. Below are the code snippets that I am using but none of the is working. How can make this work?
nodejs代码在这里是index.js
nodejs code here is index.js
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let newRoute = require('./routes/new');
io.on('connection', (socket) => {
console.log('Listening to Socket');
socket.on('FirstEvent', msg => {
console.log(msg); // This works fine, no issues here and question is not for this.
});
});
app.use((req, res, next) => {
req.io = io;
next();
});
app.use('/new', newRoute);
var port = process.env.PORT || 3001;
http.listen(port, function() {
console.log('listening in http://localhost:' + port);
});
这是new.js
let express = require('express');
let route = express.Router();
route.get('/', (request, response) => {
console.log('NEW ROUTE'); // this is logs out.
request.io.on('RouteEvent', msg => {
console.log(msg); // this does not pop out
});
response.json({
'RES': 'No Socket IO data'
});
});
module.exports = route;
这是我的home.ts文件,其中使用离子3在前端侧添加以下代码
Here is my home.ts file with following code on front end side using ionic 3
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestServiceProvider } from '../../providers/rest-service/rest-service';
import { Socket } from 'ng-socket-io';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
nickname = '';
constructor(public navCtrl: NavController, private socket: Socket, private rest: RestServiceProvider) { }
joinChat() {
this.socket.connect();
this.socket.emit('FirstEvent', {
'FirstEvent': 'AN EVENT TRAGETTED TO index.js ON SERVER SIDE'
});
this.rest.get().subscribe(response => {
console.log('A LOG AFTER CALLING REST GET FUNCTION'); //
console.log('RESPONSE FROM THE SERVER: ', response);
this.socket.emit('RouteEvent', {
'RouteEvent': 'AN EVENT SENT TO THE ROUTE ON SERVER SIDE'
});
});
}
}
这是我的休息服务
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
/*
Generated class for the RestServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class RestServiceProvider {
constructor(public http: HttpClient) {
console.log('Hello RestServiceProvider Provider');
}
get() {
console.log('GETTTTTT');
return this.http.get('http://localhost:3001/new');
}
}
我在这里犯了什么错误?
Where is the mistake I am making here?
这是更新
我还在等待解决方案.
我也尝试了以下方法.我将路由包装到一个函数中,并在需要时将io作为参数传递给了index.js文件.
I also tried this following approach. I wrapped the route into a function and passed io as a parameter at the time of requiring in index.js file.
这是我的new.js文件
Here is my new.js file
let express = require('express');
let route = express.Router();
module.exports = (io) => {
console.log(io);
route.get('/', (request, response) => {
console.log(io);
io.on('RouteEvent', msg => {
console.log(msg);
});
response.json({
'RES': 'No Socket IO data'
});
});
}
这是我的index.js文件
Here is my index.js file
let express = require('express');
let app = express();
let server = app.listen(3001);
let io = require('socket.io')(server);
let cors = require('cors');
app.use(cors());
let newRoute = require('./routes/new')(io); // this returns 404 not found
console.log('Server listening at port 3000');
以上方法返回当我从客户端发出请求时找不到的路由404(与上面相同).然后我将app.use()添加到下面的newRoute中.
The above approach returns the the route 404 not found when I make a request from client(which is the same as above). Then I added app.use() to newRoute which is below.
let newRoute = require('./routes/new')(io);
app.use('/new', newRoute);
然后它开始返回以下错误.
Then it started returning below error.
TypeError: Router.use() requires a middleware function but got a undefined
任何想法我在哪里做错了以及解决方案?
Any idea where am I doing it wrong and the solution?
推荐答案
您在更新的解决方案中遇到的TypeError是因为在new.js
中,您导出的函数返回的是未定义的(因为没有return语句) .如果您返回路线,则您的代码应该可以工作:
The TypeError you're getting in your updated solution is because in new.js
, the function you're exporting is returning undefined (because there's no return statement). If you return the route, your code should work:
const express = require('express');
const route = express.Router();
module.exports = (io) => {
console.log(io);
route.get('/', (request, response) => {
console.log(io);
io.on('RouteEvent', msg => {
console.log(msg);
});
response.json({
'RES': 'No Socket IO data'
});
});
return route; // add this return statement
}
这篇关于Socket.io与Express.js路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!