为什么我的AngularJS / EX preSS / Socket.io应用服务于socket.io.js文件? [英] Why isn't my AngularJS/Express/Socket.io app serving the socket.io.js file?

查看:291
本文介绍了为什么我的AngularJS / EX preSS / Socket.io应用服务于socket.io.js文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角/应用的NodeJS与Socket.io支持增加在一些实时功能。

我想补充的MongoDB和PassportJS支持,所以我已经迁移到发电机角fullstack 结构。

突然,Socket.io功能不工作了。

一个错误,我发现的是,客户端的JS库在通过Socket.io服 HTTP://localhost/socket.io/socket.io.js 现在从我的应用程序返回的index.html页面。

这听起来像一个路径问题,所以这里是我的路由配置:

的lib / routes.js(的NodeJS):

  module.exports =功能(应用程序){    //服务器API路线
    app.get('/ API / awesomeThings',api.awesomeThings);    app.post('/ API /用户,users.create);
    app.put('/ API /用户,users.changePassword);
    app.get('/ API /用户/我',users.me);
    app.get('/ API /用户/:身份证',users.show);    app.post('/ API /会话,session.login);
    app.del('/ API /会话,session.logout);    //其他所有航线使用在app /脚本/ app.js角路由
    app.get('/谐音/ *',index.partials);
    app.get('/ *',middleware.setUserCookie,index.index);    app.get('/:会话,功能(REQ,RES){
        res.render('意见/ index.html的',{
            标题:焊接火花
        });
    });};

应用/脚本/ app.js(AngularJS):

  angular.module('weld.common')。配置(函数($ routeProvider,$ locationProvider,$ httpProvider){
    $ routeProvider
        。当('/主',{
            templateUrl:'谐音/主',
            控制器:'MainCtrl
        })
        。当('/登录',{
            templateUrl:'谐音/登录',
            控制器:'LoginCtrl
        })
        。当('/注册',{
            templateUrl:'谐音/注册,
            控制器:'SignupCtrl
        })
        。当('/设置,{
            templateUrl:'谐音/设置
            控制器:'SettingsCtrl',
            验证:真
        })
        。当('/:会话',{
            templateUrl:意见/ UI编辑器/ editor.html',
            控制器:'weldEditorController
        })
        。除此以外({
            redirectTo:/我的项目
        });    $ locationProvider.html5Mode(真).hash preFIX(!); // TODO:测试并找出如何工作在IE    //拦截401S和403s和重定向您登录
    $ httpProvider.interceptors.push(['$ Q','$位置',函数($ Q $位置){
        返回{
            responseError':功能(响应){
                如果(response.status === 401 || response.status === 403){
                    $ location.path('/登录');
                    返回$ q.reject(响应);
                }
                其他{
                    返回$ q.reject(响应);
                }
            }
        };
    }]);})
.RUN(函数($ rootScope,$位置,验证){    //如果重定向路由需要身份验证登录,你没有登录
    $ rootScope。在$('$ routeChangeStart',函数(事件,旁边){
        如果(next.authenticate&放大器;&放大器;!Auth.isLoggedIn()){
            $ location.path('/登录');
        }
    });});

任何想法,为什么socket.io航线被打破?

更新:整个server.js:

  //初始化前preSS框架和Socket.io
VAR前preSS =要求('前preSS),
    PATH =要求(路径),
    FS =要求(FS),
    猫鼬=要求('猫鼬'),
    HTTP =要求(HTTP),
    socketio =要求('socket.io');process.env.NODE_ENV = process.env.NODE_ENV || 发展;//应用程序配置
无功配置=要求('./的lib /配置/配置');//连接到数据库
变种DB = mongoose.connect(config.mongo.uri,config.mongo.options);//引导模式
VAR modelsPath = path.join(__目录名称,LIB /模型');
fs.readdirSync(modelsPath).forEach(功能(文​​件){
  需要(modelsPath +'/'+文件);
});//使用样例数据填充空数据库
要求('./的lib /配置/ dummydata');//护照配置
要求('./的lib /配置/护照')();//初始化应用程序和Web服务器
VAR应用=前preSS();
VAR服务器= http.createServer(应用程序);//初始化Socket.io服务器
VAR IO = socketio.listen(服务器);
app.set('socket.io.log.level',process.env.SOCKET_IO_LOG_LEVEL || 1);
要求('./的lib /插座')(IO,app.get('socket.io.log.level'));// Heroku的网络插座解决方法
// https://devcenter.heroku.com/articles/getting-started-with-nodejs
// https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
io.configure(函数(){
    io.set('运输',['XHR轮询']);
    io.set('轮询持续时间',10);
});//防爆preSS设置
要求('./的lib /配置/ EX preSS')(应用程序);//路由
要求('./的lib /路径')(应用程序);//网址:启动服务器
app.listen(config.port,函数(){
  的console.log('前preSS服务器上运行的http://本地主机:在%s模式%D',config.port,app.get('ENV'));
});//揭露应用
出口= module.exports =应用;


解决方案

Socket.io是听服务器 VAR IO = socketio.listen (服务器);

应用正在监听的端口,而不是服务器

变更

  app.listen(config.port,函数(){
  的console.log('前preSS服务器上运行的http://本地主机:在%s模式%D',config.port,
app.get('ENV'));
});

  server.listen(config.port,函数(){
  的console.log('前preSS服务器上运行的http://本地主机:在%s模式%D',config.port,app.get('ENV'));
});

I have an Angular/NodeJS app, with Socket.io support added in for some real-time features.

I wanted to add MongoDB and PassportJS support so I have migrated to the generator-angular-fullstack structure.

Suddenly, the Socket.io features don't work anymore.

One error I've found is that the client-side JS library served by Socket.io at http://localhost/socket.io/socket.io.js now returns the index.html page from my app instead.

That sounds like a routing problem, so here is my routing configurations:

lib/routes.js (NodeJS):

module.exports = function(app) {

    // Server API Routes
    app.get('/api/awesomeThings', api.awesomeThings);

    app.post('/api/users', users.create);
    app.put('/api/users', users.changePassword);
    app.get('/api/users/me', users.me);
    app.get('/api/users/:id', users.show);

    app.post('/api/session', session.login);
    app.del('/api/session', session.logout);

    // All other routes to use Angular routing in app/scripts/app.js
    app.get('/partials/*', index.partials);
    app.get('/*', middleware.setUserCookie, index.index);

    app.get('/:session', function(req, res) {
        res.render('views/index.html', {
            title: 'Weld Spark'
        });
    });

};

app/scripts/app.js (AngularJS):

angular.module('weld.common').config(function($routeProvider, $locationProvider, $httpProvider) {
    $routeProvider
        .when('/main', {
            templateUrl: 'partials/main',
            controller: 'MainCtrl'
        })
        .when('/login', {
            templateUrl: 'partials/login',
            controller: 'LoginCtrl'
        })
        .when('/signup', {
            templateUrl: 'partials/signup',
            controller: 'SignupCtrl'
        })
        .when('/settings', {
            templateUrl: 'partials/settings',
            controller: 'SettingsCtrl',
            authenticate: true
        })
        .when('/:session', {
            templateUrl: 'views/ui-editor/editor.html',
            controller: 'weldEditorController'
        })
        .otherwise({
            redirectTo: '/my-project'
        });

    $locationProvider.html5Mode(true).hashPrefix('!'); // TODO: Test and figure out how this works in IE

    // Intercept 401s and 403s and redirect you to login
    $httpProvider.interceptors.push(['$q', '$location', function($q, $location) {
        return {
            'responseError': function(response) {
                if(response.status === 401 || response.status === 403) {
                    $location.path('/login');
                    return $q.reject(response);
                }
                else {
                    return $q.reject(response);
                }
            }
        };
    }]);

})
.run(function ($rootScope, $location, Auth) {

    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$routeChangeStart', function (event, next) {
        if (next.authenticate && !Auth.isLoggedIn()) {
            $location.path('/login');
        }
    });

});

Any ideas why the socket.io route is broken?

UPDATE: entire server.js:

// Init Express framework and Socket.io
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    mongoose = require('mongoose'),
    http = require('http'),
    socketio = require('socket.io');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

// Application Config
var config = require('./lib/config/config');

// Connect to database
var db = mongoose.connect(config.mongo.uri, config.mongo.options);

// Bootstrap models
var modelsPath = path.join(__dirname, 'lib/models');
fs.readdirSync(modelsPath).forEach(function (file) {
  require(modelsPath + '/' + file);
});

// Populate empty database with sample data
require('./lib/config/dummydata');

// Passport Configuration
require('./lib/config/passport')();

// Init app and web server
var app = express();
var server = http.createServer(app);

// Init Socket.io server
var io = socketio.listen(server);
app.set('socket.io.log.level', process.env.SOCKET_IO_LOG_LEVEL || 1);
require('./lib/socket')(io, app.get('socket.io.log.level'));

// Heroku web socket workaround
//   https://devcenter.heroku.com/articles/getting-started-with-nodejs
//   https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
io.configure(function() {
    io.set('transports', ['xhr-polling']);
    io.set('polling duration', 10);
});

// Express settings
require('./lib/config/express')(app);

// Routing
require('./lib/routes')(app);

// Web: Start server
app.listen(config.port, function () {
  console.log('Express server running on http://localhost:%d in %s mode', config.port, app.get('env'));
});

// Expose app
exports = module.exports = app;

解决方案

Socket.io is listening to server with var io = socketio.listen(server);.

app is listening to the port, not server.

change

app.listen(config.port, function () {
  console.log('Express server running on http://localhost:%d in %s mode', config.port,
app.get('env'));
});

to

server.listen(config.port, function () {
  console.log('Express server running on http://localhost:%d in %s mode', config.port, app.get('env'));
});

这篇关于为什么我的AngularJS / EX preSS / Socket.io应用服务于socket.io.js文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆