I have a scenario which I need to create a very simple text chat using nodejs
and Websocket
.
I have everything set up and working.
I now need to allow users to send a parameter in the websocket connection
URL.
Like so: websocket = new WebSocket("ws://test-website.net:8080/?id=55");
in my reserach I came across quite a few similar questions and found out that I can pass the parameters in the URL like the example above.
However, none of them mentions or explains how to get this parameter ( 55 in this example ) in server.js
wss.on('connection', function(ws) {
///I need to get the parameter here////
});
Could someone please advice on this issue?
Thanks in advance.
In your websocket request handler, it is normally passed the web socket as the first argument; the incoming HTTP request is passed as a second argument:
webSocketServer.on('connection', function connection(ws_client_stream, incoming_request) {
console.log(incoming_request.url);
});
From there, you can use url.parse
to get the components of the URL, such as the query string that you are interested in.
For websocket library in nodejs (websocket.js npm) :
wsServer.on('request', function(request){
var FullURL = request.resourceURL.query;
console.log(FullURL);
// . . your code . . //
}
link = wss://localhost/?param=value
output
{ param : 'value' }
here request.resourceURL retuen a object
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?id=65&encoding=text',
query: { id: '65', encoding: 'text' },
pathname: '/',
path: '/?id=65&encoding=text',
href: '/?id=65&encoding=text' }
If you're using 'websocket' lib, the following code retrieves your queryStrings:
wsServer.on('request', function(request)
{
console.log(request.resourceURL.query);
}
Note 1: You don't need to parse anything here.
Note 2: Though it has been answered years ago, this answer goes to those in case where people find the above-mentioned answer more complicated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.