使用 Node.js、express 和 socket.io 在 OpenShift 上访问控制允许源 [英] Access-Control-Allow-Origin on OpenShift using Node.js, express, and socket.io

查看:16
本文介绍了使用 Node.js、express 和 socket.io 在 OpenShift 上访问控制允许源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As the title suggests, I'm having trouble remotely accessing my node.js instance hosted on OpenShift. The error I keep getting in my browser's console looks like this:

XMLHttpRequest 无法加载 http://app-domain.rhcloud.com:8000/socket.io/?EIO=3&transport=polling&t=1430117973290-2.请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://localhost:8383' 因此不允许访问.响应的 HTTP 状态代码为 503.(08:59:33:579 | 错误,javascript)在 public_html/index.html

XMLHttpRequest cannot load http://app-domain.rhcloud.com:8000/socket.io/?EIO=3&transport=polling&t=1430117973290-2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. The response had HTTP status code 503. (08:59:33:579 | error, javascript) at public_html/index.html

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

I realize that the headers need to be set to allow cross-domain requests and I've tried several different variations of doing that in my server code.

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

Currently the server and client code looks like this:

服务器:

#!/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();
   });
});

非常感谢任何帮助或指示!

Any help or pointers are greatly appreciated!

推荐答案

事实证明我在 OpenShift 上的应用程序的 NodeJS 盒有问题.我不得不完全重新创建应用程序.创建后,我从创建应用程序后 OpenShift 提供的 git 存储库中克隆了默认项目.我更新了 server.js 文件以包含上面问题中来自Server"的代码.

It turns out the NodeJS cartridge of my application on OpenShift was faulty. I had to re-create the application completely. After creation I cloned the default project from the git repository OpenShift provides once your application is created. I updated the server.js file to contain the code from "Server" in my question above.

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

After that, I completed the following steps:

  1. npm install express --save
  2. npm install socket.io --save
  3. git 添加.
  4. git commit -m '更新'
  5. git push

注意:

--save"参数强制更新您的package.json",其中包含您在服务器项目中使用的模块的定义.OpenShift 使用它来自动(据我所知)下载服务器端需要的模块.就我而言,似乎是在 git push 之后提交了 express 和 socket.io,这意味着它可能覆盖了服务器端模块.

The "--save" parameter forces an update of your "package.json' which contains the definitions for what modules you are using in your server project. OpenShift uses this to automatically (as far as I can tell) download the required modules on the server-side. In my case, it appears that the express and socket.io got committed after the git push, which means it probably overwrote the server-side modules.

无论如何,我用上面的客户端"js启动了我的本地网站项目,它工作正常.希望这能帮助其他人在 OpenShift 中苦苦挣扎.

Anyway, I fired up my local website project with the "Client" js above and it works fine. Hope this helps someone else struggling with OpenShift.

这篇关于使用 Node.js、express 和 socket.io 在 OpenShift 上访问控制允许源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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