From d006c3db6b37221f3b977a45cb18b52ff310a705 Mon Sep 17 00:00:00 2001 From: Mohamed Ali Elsayed Date: Tue, 7 Jan 2025 18:28:37 +0300 Subject: [PATCH] Refactored WebSocket URL construction into a separate constructWebSocketURL method and updated login/logout API paths to use relative URLs instead of absolute paths. --- src/views/components/AppLogin.js | 2 +- src/views/components/AppLogout.js | 2 +- src/views/index.html | 26 +++++++++++++++++--------- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/views/components/AppLogin.js b/src/views/components/AppLogin.js index 81f0c3c..3300af6 100644 --- a/src/views/components/AppLogin.js +++ b/src/views/components/AppLogin.js @@ -26,7 +26,7 @@ export default { }, async submitApi() { try { - let response = await window.http.get(`./app/login`) + let response = await window.http.get(`app/login`) let results = response.data.results; this.login_link = results.qr_link; this.login_duration_sec = results.qr_duration; diff --git a/src/views/components/AppLogout.js b/src/views/components/AppLogout.js index bc1d66d..1e87c8f 100644 --- a/src/views/components/AppLogout.js +++ b/src/views/components/AppLogout.js @@ -15,7 +15,7 @@ export default { async submitApi() { try { - await http.get(`./app/logout`) + await http.get(`app/logout`) } catch (error) { if (error.response) { throw Error(error.response.data.message) diff --git a/src/views/index.html b/src/views/index.html index 226ccd8..1a8ce5a 100644 --- a/src/views/index.html +++ b/src/views/index.html @@ -180,6 +180,17 @@ }); } + const constructWebSocketURL = () => { + const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://'; + const path = location.pathname + // Remove trailing slash + .replace(/\/+$/, '') + // Remove double slashes + .replace(/\/+/g, '/'); + + return `${protocol}${location.host}${path}/ws`; + }; + Vue.createApp({ components: { AppLogin, AppLoginWithCode, AppLogout, AppReconnect, @@ -203,15 +214,7 @@ }, mounted() { if (window["WebSocket"]) { - let wsType = location.protocol !== 'https:' ? 'ws://' : 'wss://'; - let path = document.location.pathname; // Get the full path including the subfolder - // Remove trailing slash if any - if (path.endsWith('/')) { - path = path.slice(0, -1); - } - // Construct the WebSocket URL with the full path - this.app_ws = new WebSocket(wsType + document.location.host + path + "/ws"); - + this.app_ws = new WebSocket(constructWebSocketURL()); this.app_ws.onopen = (evt) => { this.app_ws.send(JSON.stringify({ @@ -219,6 +222,11 @@ "message": "List device" })) }; + + this.app_ws.onerror = (error) => { + console.error('WebSocket error:', error); + showErrorInfo('Connection error occurred. Please refresh the page.'); + }; this.app_ws.onmessage = (evt) => { const message = JSON.parse(evt.data)