使用Node.js,Express和socket.io的OpenShift上的Access-Control-Allow-Origin [英] Access-Control-Allow-Origin on OpenShift using Node.js, express, and socket.io

查看:100
本文介绍了使用Node.js,Express和socket.io的OpenShift上的Access-Control-Allow-Origin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

顾名思义,我无法远程访问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"标头.因此,不允许访问来源" 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盒式磁带有问题.我不得不完全重新创建该应用程序.创建完成后,一旦您创建了应用程序,我便从git存储库中克隆了默认项目,OpenShift提供了该项目.我更新了server.js文件,以包含上述问题中"服务器"中的代码.

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 add.
  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.

无论如何,我使用上面的" Client " 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上的Access-Control-Allow-Origin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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