HTTP headers in Websockets client API

后端 未结 11 2432
情话喂你
情话喂你 2020-11-22 10:41

Looks like it\'s easy to add custom HTTP headers to your websocket client with any HTTP header client which supports this, but I can\'t find how to do it with the JSON API.

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 10:50

    Totally hacked it like this, thanks to kanaka's answer.

    Client:

    var ws = new WebSocket(
        'ws://localhost:8080/connect/' + this.state.room.id, 
        store('token') || cookie('token') 
    );
    

    Server (using Koa2 in this example, but should be similar wherever):

    var url = ctx.websocket.upgradeReq.url; // can use to get url/query params
    var authToken = ctx.websocket.upgradeReq.headers['sec-websocket-protocol'];
    // Can then decode the auth token and do any session/user stuff...
    

提交回复
热议问题