Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter in websocket uri on react-native is not working

I need to implement websocket connection for my react-native application.
My problem is I always get:

Unable to set ws://www.needseek.com:31337?partyId="a3e75250-d1a3-11e7-9116-a7b8f75cfbc6"&sessionToken="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXJ0eUlkIjoiYTNlNzUyNTAtZDFhMy0xMWU3LTkxMTYtYTdiOGY3NWNmYmM2Iiwibm9uY2UiOiIxNTExNTkxNTQyNDE3MDAiLCJpYXQiOjE1MTE1OTE1NDJ9.HVfHRlXbcUZgkTFfL42YGd0LGtCUjnJuQ5ju3S1alOk" as default origin header.

Here's the code that I used:

let wsUrl = 'ws://www.needseek.com:31337?partyId="' + user.profile.partyId + '"&sessionToken="'+ user.sessionToken + '"';
console.log( 'Websocket Url', wsUrl );

var ws = new WebSocket( wsUrl );

ws.onopen = () => {
  // connection opened
  ws.send('Connection open..');
  console.log('Connection open..');
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

Also, I read the react-native documentation about implementing websocket -> https://facebook.github.io/react-native/docs/network.html

like image 546
wedev27 Avatar asked Nov 25 '17 13:11

wedev27


1 Answers

I found the answer. Just use encodeURI() syntax and before passing the websocket url to WebSocket instance.

let wsUrl = encodeURI('ws://www.needseek.com:31337?partyId="' + user.profile.partyId + '"&sessionToken="'+ user.sessionToken + '"');
console.log( 'Websocket Url', wsUrl );

var ws = new WebSocket( wsUrl );

This works for me.

like image 195
wedev27 Avatar answered Sep 29 '22 11:09

wedev27