简体   繁体   English

未捕获的类型错误:无法读取未定义的属性“indexOf”

[英]Uncaught TypeError: Cannot read property 'indexOf' of undefined

I finally got my javascript references with no 404. The first info I fill out into the html form gives me console errors.我终于得到了没有 404 的 javascript 引用。我填写到 html 表单中的第一个信息给了我控制台错误。

Here is my JavaScript that is causing me an issue:这是我的 JavaScript,导致我出现问题:

/* global define, module, require */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['crypto-js', 'ws'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node. Export.
        module.exports = factory(require('crypto-js'), require('ws'));
    } else {
        // Browser globals (root is window)
        root.GameSparks = factory(root.CryptoJS, root.WebSocket || root.MozWebSocket);
    }
}(this, function(CryptoJS, WebSocket) {

var GameSparks = function() {};

GameSparks.prototype = {

    init: function(options) {
        this.options = options;
        this.socketUrl = options.url;

        this.pendingRequests = {};
        this.requestCounter = 0;

        this.connect();
    },

    buildServiceUrl: function(live, options) {
        var stage;
        var urlAddition = options.key;
        var credential;
        var index;

        if (live) {
          stage = "live";
        } else {
          stage = "preview";
        }

        if (!options.credential || options.credential.length === 0) {
          credential = "device";
        } else {
          credential = options.credential;
        }

        index = options.secret.indexOf(":");
        if (index > 0) {
            credential = "secure";

            urlAddition = options.secret.substr(0, index) + "/" + urlAddition;
        }

        return "wss://" + stage + "-" + urlAddition + ".ws.gamesparks.net/ws/" + credential + "/" + urlAddition;
    },

    initPreview: function(options) {
        options.url = this.buildServiceUrl(false, options);
        this.init(options);
    },

    initLive: function(options) {
        options.url = this.buildServiceUrl(true, options);
        this.init(options);
    },

    reset: function() {
        this.initialised = false;
        this.connected = false;
        this.error = false;
        this.disconnected = false;

        if (this.webSocket != null){
            this.webSocket.onclose = null;
            this.webSocket.close();
        }
    },

    connect: function() {
        this.reset();

        try {
            this.webSocket = new WebSocket(this.socketUrl);
            this.webSocket.onopen = this.onWebSocketOpen.bind(this);
            this.webSocket.onclose = this.onWebSocketClose.bind(this);
            this.webSocket.onerror = this.onWebSocketError.bind(this);
            this.webSocket.onmessage = this.onWebSocketMessage.bind(this);
        } catch(e) {
            this.log(e.message);
        }
    },

    disconnect: function() {
        if (this.webSocket && this.connected) {
            this.disconnected = true;
            this.webSocket.close();
        }
    },

    onWebSocketOpen: function(ev) {
        this.log('WebSocket onOpen');

        if (this.options.onOpen) {
            this.options.onOpen(ev);
        }

        this.connected = true;
    },

    onWebSocketClose: function(ev) {
        this.log('WebSocket onClose');

        if (this.options.onClose) {
            this.options.onClose(ev);
        }

        this.connected = false;

        // Attemp a re-connection if not in error state or deliberately disconnected.
        if (!this.error && !this.disconnected) {
            this.connect();
        }
    },

    onWebSocketError: function(ev) {

        this.log('WebSocket onError: Sorry, but there is some problem with your socket or the server is down');

        if (this.options.onError) {
            this.options.onError(ev);
        }

        // Reset the socketUrl to the original.
        this.socketUrl = this.options.url;

        this.error = true;
    },

    onWebSocketMessage: function(message) {
        this.log('WebSocket onMessage: ' + message.data);

        var result;
        try {
            result = JSON.parse(message.data);
        } catch (e) {
            this.log('An error ocurred while parsing the JSON Data: ' + message + '; Error: ' + e);
            return;
        }

        if (this.options.onMessage) {
            this.options.onMessage(result);
        }

        // Extract any auth token.
        if (result['authToken']) {
            this.authToken = result['authToken'];
            delete result['authToken'];
        }

        if (result['connectUrl']) {
            // Any time a connectUrl is in the response we should update and reconnect.
            this.socketUrl = result['connectUrl'];
            this.connect();
        }

        var resultType = result['@class'];

        if (resultType === '.AuthenticatedConnectResponse') {
            this.handshake(result);
        } else if (resultType.match(/Response$/)){
            if (result['requestId']) {
                var requestId = result['requestId'];
                delete result['requestId'];

                if (this.pendingRequests[requestId]) {
                    this.pendingRequests[requestId](result);
                    this.pendingRequests[requestId] = null;
                }
            }
        }

    },

    handshake: function(result) {

        if (result['nonce']) {

            var hmac;

            if (this.options.onNonce) {
                hmac = this.options.onNonce(result['nonce']);
            } else {
                hmac = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(result['nonce'], this.options.secret));
            }

            var toSend = {
                '@class' : '.AuthenticatedConnectRequest',
                hmac : hmac
            };

            if (this.authToken) {
                toSend.authToken = this.authToken;
            }

            if (this.sessionId) {
                toSend.sessionId = this.sessionId;
            }

            const browserData = this.getBrowserData();
            toSend.platform = browserData.browser;
            toSend.os = browserData.operatingSystem;

            this.webSocketSend(toSend);

        } else if (result['sessionId']) {
            this.sessionId = result['sessionId'];
            this.initialised = true;

            if (this.options.onInit) {
                this.options.onInit();
            }

            this.keepAliveInterval = window.setInterval(this.keepAlive.bind(this), 30000);
        }
    },

    keepAlive: function() {
        if (this.initialised && this.connected) {
            this.webSocket.send(' ');
        }
    },

    send: function(requestType, onResponse){
        this.sendWithData(requestType, {}, onResponse);
    },

    sendWithData: function(requestType, json, onResponse) {
        if (!this.initialised) {
            onResponse({ error: 'NOT_INITIALISED' });
            return;
        }

        // Ensure requestType starts with a dot.
        if (requestType.indexOf('.') !== 0) {
            requestType = '.' + requestType;
        }

        json['@class'] = requestType;

        json.requestId = (new Date()).getTime() + "_" + (++this.requestCounter);

        if (onResponse != null) {
            this.pendingRequests[json.requestId] = onResponse;
            // Time out handler.
            setTimeout((function() {
                if (this.pendingRequests[json.requestId]) {
                    this.pendingRequests[json.requestId]({ error: 'NO_RESPONSE' });
                }
            }).bind(this), 32000);
        }

        this.webSocketSend(json);
    },

    webSocketSend: function(data) {

        if (this.options.onSend) {
            this.options.onSend(data);
        }

        var requestString = JSON.stringify(data);
        this.log('WebSocket send: ' + requestString);
        this.webSocket.send(requestString);
    },

    getSocketUrl: function() {
        return this.socketUrl;
    },

    getSessionId: function() {
        return this.sessionId;
    },

    getAuthToken: function() {
        return this.authToken;
    },

    setAuthToken: function(authToken) {
        this.authToken = authToken;
    },

    isConnected: function() {
        return this.connected;
    },

    log: function(message) {
        if (this.options.logger) {
            this.options.logger(message);
        }
    },

    getBrowserData: function() {

        var browsers = [
            {
                string: navigator.userAgent,
                subString: 'Chrome',
                identity: 'Chrome'
            },
            {   string: navigator.userAgent,
                subString: 'OmniWeb',
                versionSearch: 'OmniWeb/',
                identity: 'OmniWeb'
            },
            {
                string: navigator.vendor,
                subString: 'Apple',
                identity: 'Safari',
                versionSearch: 'Version'
            },
            {
                prop: window.opera,
                identity: 'Opera',
                versionSearch: 'Version'
            },
            {
                string: navigator.vendor,
                subString: 'iCab',
                identity: 'iCab'
            },
            {
                string: navigator.vendor,
                subString: 'KDE',
                identity: 'Konqueror'
            },
            {
                string: navigator.userAgent,
                subString: 'Firefox',
                identity: 'Firefox'
            },
            {
                string: navigator.vendor,
                subString: 'Camino',
                identity: 'Camino'
            },
            {
                string: navigator.userAgent,
                subString: 'Netscape',
                identity: 'Netscape'
            },
            {
                string: navigator.userAgent,
                subString: 'MSIE',
                identity: 'Explorer',
                versionSearch: 'MSIE'
            },
            {
                string: navigator.userAgent,
                subString: 'Gecko',
                identity: 'Mozilla',
                versionSearch: 'rv'
            },
            {
                string: navigator.userAgent,
                subString: 'Mozilla',
                identity: 'Netscape',
                versionSearch: 'Mozilla'
            }
        ];

        var operatingSystems = [
            {
                string: navigator.platform,
                subString: 'Win',
                identity: 'Windows'
            },
            {
                string: navigator.platform,
                subString: 'Mac',
                identity: 'Mac'
            },
            {
               string: navigator.userAgent,
               subString: 'iPhone',
               identity: 'iPhone/iPod'
            },
            {
                string: navigator.platform,
                subString: 'Linux',
                identity: 'Linux'
            }
        ];

        function searchForIdentity(data) {
            for (var i = 0; i < data.length; i++) {
                var string = data[i].string;
                var prop = data[i].prop;

                if (string) {
                    // Look for the sub string in the string.
                    if (string.indexOf(data[i].subString) !== -1) {
                        return data[i].identity;
                    }
                } else if (prop) {
                    return data[i].identity;
                }
            }
        }

        return {
            browser: searchForIdentity(browsers),
            operatingSystem: searchForIdentity(operatingSystems)
        };
    }
};

return GameSparks;

}));

As you probably saw, the line that is giving me issue is:正如您可能看到的,给我带来问题的那一行是:

index = options.secret.indexOf(":");
            if (index > 0) {
                credential = "secure";

I have no idea what the issue is.我不知道是什么问题。 It is a backend server, and I know they suggested I use a third party server to encrypt my API key...这是一个后端服务器,我知道他们建议我使用第三方服务器来加密我的 API 密钥......

I revisited the SDK, and it looks like the devs had issued an update.我重新访问了 SDK,看起来开发人员已经发布了更新。 I was, strangely using the updated javascript, but not the updated html file the references the new js.奇怪的是,我使用更新的 javascript,而不是更新的 html 文件引用了新的 js。 With the API key and secret, I can handshake perfectly now.有了API key和secret,我现在可以完美握手了。

No begins the long battle of customizing the UI and content!没有开始定制 UI 和内容的长期战斗!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的类型错误:无法读取未定义的属性“indexOf” - Uncaught TypeError: Cannot read property 'indexOf' of undefined CkEditor:未捕获的TypeError:无法读取未定义的属性&#39;indexOf&#39; - CkEditor: Uncaught TypeError: Cannot read property 'indexOf' of undefined video.load() 未捕获类型错误:无法读取未定义的属性“indexOf” - video .load() Uncaught TypeError: Cannot read property 'indexOf' of undefined Javascript TypeError:无法读取undefined的属性'indexOf' - Javascript TypeError: Cannot read property 'indexOf' of undefined 我从哪里开始出现此jQuery / WordPress错误? 未捕获的TypeError:无法读取未定义的属性&#39;indexOf&#39; - Where do I begin with this jQuery/WordPress error? Uncaught TypeError: Cannot read property 'indexOf' of undefined JQuery on单选按钮单击Uncaught throw TypeError:无法读取未定义的属性&#39;indexOf&#39; - JQuery on radio button click Uncaught throwing TypeError: Cannot read property 'indexOf' of undefined bxslider指令抛出错误`Uncaught TypeError:无法读取未定义`的属性&#39;indexOf&#39; - bxslider directive throwing error `Uncaught TypeError: Cannot read property 'indexOf' of undefined` 我收到一个错误 - 未捕获的类型错误:无法读取未定义的属性“indexOf” - I am getting an error- Uncaught TypeError: Cannot read property 'indexOf' of undefined 未捕获的TypeError:无法读取未定义的属性&#39;indexOf&#39;(observer-scripts.js) - Uncaught TypeError: Cannot read property 'indexOf' of undefined (observer-scripts.js) 未捕获的类型错误:无法使用 proengsoft / laravel-jsvalidation 读取未定义的属性“indexOf” - Uncaught TypeError: Cannot read property 'indexOf' of undefined, with proengsoft / laravel-jsvalidation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM