Sending cookies with react native websockets

后端 未结 3 1253
醉酒成梦
醉酒成梦 2020-12-31 17:46

So I\'m using react native websockets but cannot figure out how i can include cookies in websockets, any suggestions?

相关标签:
3条回答
  • 2020-12-31 18:07

    If you look at the WebSocket declaration, you can see that the header keys should be strings.

    This works for me:

    var headers = {};
    headers["cookie"] = `cookieName=${cookieValue}`;
    
    const ws = new WebSocket(`wss://www.somesite.com/socket`, null, {
        headers
    });
    

    not this:

    {
      headers: {
        cookie: `cookieName=${cookieValue}`
      }
    }
    
    0 讨论(0)
  • 2020-12-31 18:11

    As of React Native 0.38, this should happen automatically on Android.

    There's currently an open PR for making it work automatically on iOS as well, but at the moment it seems there's still some work left there around testing.

    In the meanwhile, you could follow the "manual approach" proposed here:

    Manual approach is to retrieve the cookie through a cookie manager plugin and pass it as headers to web socket.

    (Once you have the cookie from the manager, the way to pass it to the websocket is, as mentioned previously, to use the undocumented 3rd parameter of WebSocket.)

    0 讨论(0)
  • 2020-12-31 18:25

    At the moment there is no automatic way to do it. There is a third (undocumented) parameter for the WebSocket constructor to pass custom HTTP headers to the connect request.

    WebSocket(url, '', {Cookie: 'key=value'});
    

    This works on iOS, I haven't tested it on Android but the WebSocket implementation looks like it is supported there as well.

    If you just need to pass a session id or auth token, it's probably easier to pass it as a GET param in the url. Relying on undocumented behavior in a rapidly changing framework can be dangerous.

    0 讨论(0)
提交回复
热议问题