带有Express.js路由的Socket.io

时间:2017-12-18 22:29:04

标签: javascript node.js angular express socket.io

我正在使用带有其路由的expressjs的socketio作为中间件。以下是我的代码。目前,我的设置无法使用我当前的方法。以下是我正在使用的代码片段,但没有一个正在运行。如何使这项工作?

这里的nodejs代码是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

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');
    }

}

我在这里犯的错误在哪里?

这是最新消息

我还在等待解决方案。

我也试过以下方法。我将路由包装到一个函数中,并在index.js文件中要求时将io作为参数传递。

这是我的new.js文件

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文件

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。

let newRoute = require('./routes/new')(io);
app.use('/new', newRoute);

然后它开始返回错误。

TypeError: Router.use() requires a middleware function but got a undefined

知道我在哪里做错了解决方案吗?

1 个答案:

答案 0 :(得分:0)

您在更新的解决方案中遇到的TypeError是因为在new.js中,您正在导出的函数返回的是未定义的(因为没有return语句)。如果您返回路线,则您的代码应该可以工作:

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
}