我在 python 中有一個簡單的 web 服務器,例如在 127.0.0.1:8080 上運行。我可以提供 http 請求和網路套接字。這是服務器路由的示例。
...
web.route('*', '/ws', ws_handler),
web.route('*', '/api/some_url', http_handler)
...
我在 Vue 2 JS 中有我的應用程式的前端部分。我vue.config.js為代理開發服務器設定了檔案。
const host = "127.0.0.1"
const port = 8080
devServer: {
proxy: {
"/api": {
target:`http://${host}:${port}/`,
secure:false
},
"/ws": {
target:`ws://${host}:${port}/`,
ws:true,
secure:false,
changeOrigin:true
}
}
}
例如,當我發出 http 請求時
let res = await axios.get('/api/some_url');
一切正常,但如果我想設定 websocket 連接
soc = new WebSocket('/ws');
我有錯誤
Failed to construct 'WebSocket': The URL '/ws' is invalid.
對于 websockets 我的設定不起作用。
如果提供完整地址,則連接建立并且一切正常。
soc = new WebSocket('ws://127.0.0.1:8080/ws');
我已經閱讀了很多文章,但沒有成功解決我的問題 - 如何為 Vue JS 開發服務器代理 websocket 連接。
uj5u.com熱心網友回復:
您應該將 WebSocket 實體化為 ws = new WebSocket('ws://' window.location.host '/ws');
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352432.html
