The front end adds Token to WebSocket

background:

I believe that developers, you have encountered or tried to modify the request header for WebSocket through the API.

Some back-end colleagues even hope that what the front-end can do is to authorize in Request Headers: Token

Note: There is no method to modify the request header in JavaScript websocket API.

you have to find another way

Solution 1 : There are parameters in the request address

const ws =  new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${url}?${token}/websocket`)

Solution 2: send to send data

const  ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}:${url}/websocket`)
ws.onopen=()=>{ws.send(token)}

Solution 3: Use Sec-WebSocket-Protocol to pass token

const url = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${url}/websocket`
const token = localStorage.getItem('token')
const ws = new WebSocket(url, [token])

If you get an error like this

ws.ts:68 Uncaught (in promise) DOMException: Failed to construct 'WebSocket': The subprotocol '"Token"' is invalid.

Please deal with your Token 

const ws = new WebSocket(url, [JSON.parse(token)])

Note: The Token response is also required when the backend responds

Of course, if you have other parameters that need to be passed in the header, you can also

const ws = new WebSocket(url, ['v10.stomp', 'v11.stomp', token])

Digression: If the backend emphasizes that you need to authorize: Token mount in Request Headers, just tell him that it can't be done.

Guess you like

Origin blog.csdn.net/m0_62326562/article/details/129838054