socketio / socket.io-client

Realtime application framework (client)
https://socket.io
10.63k stars 3.04k forks source link

How to set request headers when connect to server? #722

Closed litgh closed 3 years ago

litgh commented 10 years ago

how to set custom request headers when connect socket.io use js client

IonicaBizau commented 9 years ago

I also need that... Did you find any solution?

hayksaakian commented 9 years ago

i am also interested in this.

I've seen how to do it on the Java socket.io-client but not the JS one

Bizarrus commented 9 years ago

Won't Work with all transport-methods. If you using XHR/Ajax Polling, it is possible, but not for WebSockets on HTML5.

http://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-apic

I'm searching for a solution to.

peteruithoven commented 9 years ago

What are you trying to achieve? Can't you use url parameters?

anacronw commented 9 years ago

I'm trying to write a test to verify whether websockets can be eavesdropped on before and after authentication middleware.

In order to successfully authenticate, however, I need to send a cookie session along with the initial http upgrade request. It works in the browser, I just want it to work in my node tests as well.

bastianwegge commented 9 years ago

Is there any progress on this? Or any hint how to get/set the cookie-session / sessionId within socket.io?

anacronw commented 9 years ago

I actually got it working. The details of the initial http handshake are available at socket.request. There, you'll find the session. For example, using the socket.io middleware:

io.use(function(socket, next){
    if (!socket.request.session){
      console.log('no session in socket')
      socket.disconnect();
    }
    next();
  });
darrachequesne commented 7 years ago

Since version 2.0.0, you can now set request headers with the extraHeaders option:

const socket = io({
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});
muhammadnasr commented 6 years ago

How can I add url to this example const socket = io({ transportOptions: { polling: { extraHeaders: { 'x-clientid': 'abc' } } } });

IonicaBizau commented 6 years ago

@muhammadnasr Pass the options in the second argument, the first one being the url:

const socket = io("/your-url-here", {
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});
muhammadnasr commented 6 years ago

That's great.

Do you have sample code to set headers for iOS and Android SDK?

Thanks a lot.

thethtun-mmds commented 5 years ago

Android : https://github.com/socketio/socket.io-client-java/issues/226

shuliangfu commented 3 years ago

Can the headers be dynamically set?

darrachequesne commented 3 years ago

For future readers: please see https://socket.io/docs/v3/client-initialization/#extraHeaders