访问控制允许使用Node.js、express和socket.io在OpenShift上使用Origin

访问控制允许使用Node.js、express和socket.io在OpenShift上使用Origin,node.js,express,socket.io,openshift,access-control,Node.js,Express,Socket.io,Openshift,Access Control,正如标题所示,远程访问OpenShift上托管的node.js实例时遇到问题。我在浏览器控制台中不断遇到的错误如下所示: 无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为503。(08:59:33:579 |错误,javascript) 在public_html/index.html 我意识到需要将头设置为允许跨域请求,我在服务器代码中尝试了几种不同的方法 当前,服务器和客户端

正如标题所示,远程访问OpenShift上托管的node.js实例时遇到问题。我在浏览器控制台中不断遇到的错误如下所示:

无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为503。(08:59:33:579 |错误,javascript) 在public_html/index.html

我意识到需要将头设置为允许跨域请求,我在服务器代码中尝试了几种不同的方法

当前,服务器和客户端代码如下所示:

服务器:

#!/bin/env node
var test = {   
    init: function() {
        test.protocol = require('http');
        test.express = require('express');
        test.fs = require('fs');
        test.socket = require('socket.io');

        test.key();
        test.setup();
        test.cache();
        test.handlers();
        test.server();

        test.start();
    },

    key: function() {
        test.cache_get = function(key) { return test.zcache[key]; };
    },

    setup: function() {
        test.ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
        test.port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
    },

    cache: function() {
        if (typeof test.zcache === 'undefined') {
            test.zcache = { 'index.html': '' };
        }

        test.zcache['index.html'] = test.fs.readFileSync('./index.html');
    },

    handlers: function() {
        process.on('exit', function() { test.terminator(); });

        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'].forEach(function(element, index, array) {
            process.on(element, function() { test.terminator(element); });
        });
    },

    terminator: function() {
        if (typeof sig === 'string') {
           console.log('%s: Received %s - terminating sample app ...', Date(Date.now()), sig);
           process.exit(1);
        }

        console.log('%s: Node server stopped.', Date(Date.now()));
    },

    route: function() {
        test.routes = { };

        test.routes['/asciimo'] = function(req, res) {
            var link = 'http://i.imgur.com/kmbjB.png';
            res.send('<html><body><img src="' + link + '"></body></html>');
        };

        test.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(test.cache_get('index.html') );
        };
    },

    server: function() {
        test.route();
        test.app = test.express();

        test.app.configure(function() {
            test.app.use(function(req, res, next) {
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

                if ('OPTIONS' === req.method) {
                    res.send(200);
                }
                else {
                    next();
                };
            });
        });

        test.http = test.protocol.Server(test.app);
        test.io = test.socket(test.http);

        test.io.set('origins', '*:*');

        for (var r in test.routes) {
            test.app.get(r, test.routes[r]);
        }
    },

    start: function() {       
        test.http.listen(test.port, test.ipaddress, function() {
            test.io.sockets.on('connection', function (socket) {           
                test.config.listen(socket);
            });

            console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), test.ipaddress, test.port);
        });

        test.app.get('/', function (req, res) {
            res.sendfile('index.html');
        });
    },

    config: {
        listen: function(socket) {       
            socket.on('test', function(data) {
                socket.emit('news', data); 
            });
        }
    }
};

test.init();
var test = {
    socket: null,

    init: function() {
        try {
            //test.socket = io('ws://127.0.0.1:8080');
            test.socket = io.connect('ws://app-domain.rhcloud.com:8000');
            test.events();
        }
        catch (e) {
            alert(e.message);
        }
    },

    events: function() {
        test.socket.on('news', function (data) {
            alert(JSON.stringify(data, null, 4));
        });
    },

    send: function() {
        try {
            test.socket.emit('test', { test: 'data' });   
        }
        catch (e) {
            alert(e.message);
        }
    }
};

test.init();

$(document).ready(function() {
   $('#test').click(function() {
       test.send();
   });
});

非常感谢您的帮助和指点

我在OpenShift上的应用程序的NodeJS盒带出现了故障。我必须完全重新创建应用程序。创建之后,我从应用程序创建后OpenShift提供的git存储库克隆了默认项目。我更新了server.js文件,以包含上面问题中“server”中的代码

之后,我完成了以下步骤:

  • npm安装express--保存
  • npm安装socket.io--保存
  • git添加
  • git提交-m'update'
  • git推送
  • 注意:

    #!/bin/env node
    var test = {   
        init: function() {
            test.protocol = require('http');
            test.express = require('express');
            test.fs = require('fs');
            test.socket = require('socket.io');
    
            test.key();
            test.setup();
            test.cache();
            test.handlers();
            test.server();
    
            test.start();
        },
    
        key: function() {
            test.cache_get = function(key) { return test.zcache[key]; };
        },
    
        setup: function() {
            test.ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
            test.port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
        },
    
        cache: function() {
            if (typeof test.zcache === 'undefined') {
                test.zcache = { 'index.html': '' };
            }
    
            test.zcache['index.html'] = test.fs.readFileSync('./index.html');
        },
    
        handlers: function() {
            process.on('exit', function() { test.terminator(); });
    
            ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'].forEach(function(element, index, array) {
                process.on(element, function() { test.terminator(element); });
            });
        },
    
        terminator: function() {
            if (typeof sig === 'string') {
               console.log('%s: Received %s - terminating sample app ...', Date(Date.now()), sig);
               process.exit(1);
            }
    
            console.log('%s: Node server stopped.', Date(Date.now()));
        },
    
        route: function() {
            test.routes = { };
    
            test.routes['/asciimo'] = function(req, res) {
                var link = 'http://i.imgur.com/kmbjB.png';
                res.send('<html><body><img src="' + link + '"></body></html>');
            };
    
            test.routes['/'] = function(req, res) {
                res.setHeader('Content-Type', 'text/html');
                res.send(test.cache_get('index.html') );
            };
        },
    
        server: function() {
            test.route();
            test.app = test.express();
    
            test.app.configure(function() {
                test.app.use(function(req, res, next) {
                    res.header('Access-Control-Allow-Origin', '*');
                    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');
    
                    if ('OPTIONS' === req.method) {
                        res.send(200);
                    }
                    else {
                        next();
                    };
                });
            });
    
            test.http = test.protocol.Server(test.app);
            test.io = test.socket(test.http);
    
            test.io.set('origins', '*:*');
    
            for (var r in test.routes) {
                test.app.get(r, test.routes[r]);
            }
        },
    
        start: function() {       
            test.http.listen(test.port, test.ipaddress, function() {
                test.io.sockets.on('connection', function (socket) {           
                    test.config.listen(socket);
                });
    
                console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), test.ipaddress, test.port);
            });
    
            test.app.get('/', function (req, res) {
                res.sendfile('index.html');
            });
        },
    
        config: {
            listen: function(socket) {       
                socket.on('test', function(data) {
                    socket.emit('news', data); 
                });
            }
        }
    };
    
    test.init();
    
    var test = {
        socket: null,
    
        init: function() {
            try {
                //test.socket = io('ws://127.0.0.1:8080');
                test.socket = io.connect('ws://app-domain.rhcloud.com:8000');
                test.events();
            }
            catch (e) {
                alert(e.message);
            }
        },
    
        events: function() {
            test.socket.on('news', function (data) {
                alert(JSON.stringify(data, null, 4));
            });
        },
    
        send: function() {
            try {
                test.socket.emit('test', { test: 'data' });   
            }
            catch (e) {
                alert(e.message);
            }
        }
    };
    
    test.init();
    
    $(document).ready(function() {
       $('#test').click(function() {
           test.send();
       });
    });
    
    “--save”参数强制更新“package.json”,其中包含您在服务器项目中使用的模块的定义。OpenShift使用此参数自动(据我所知)在服务器端下载所需的模块。在我的例子中,express和socket.io似乎是在git推送之后提交的,这意味着它可能重写了服务器端模块

    无论如何,我用上面的“客户端”“js启动了我的本地网站项目,它工作得很好。希望这能帮助其他在OpenShift中挣扎的人