Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - socket.io parse requested url

I want to parse a requested url. When I used Socket.IO I had a request-object I could parse. How can I get the path from the URL?

For example:

http://localhost:4000/foo

I need to extract "foo" from the URL.

I've tried :

io.sockets.on('connection', function (socket){
    console.log(socket.handshake.address.address);
    console.log(socket.handshake.url);
}

But it they don't print "foo".

like image 392
poppel Avatar asked Mar 26 '13 13:03

poppel


People also ask

What is parse url in node JS?

js Parse URL : In this tutorial, we shall learn how to parse URL in Node. js or split a URL into readable parts and extract search parameters using built-in Node. js URL module. To parse URL in Node. js : use url module, and with the help of parse and query functions, you can extract all the components of URL.

Does Socket.IO use WSS?

Note: You can use either https or wss (respectively, http or ws ).

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.


2 Answers

BTW--Your approach is correct if you are supplying parameters to the socketio connection instead of path elements. It solved my problem when using https://github.com/pkyeck/socket.IO-objc with nodejs socketio to add params to my socket connection.

For example:

[socketIO connectToHost:@"localhost" onPort:8888 withParams:[NSDictionary dictionaryWithObject:@"52523f26f5b23538f000001c" forKey:@"player"]];

constructs URL as follows:

http://localhost:8888/socket.io/1/?t=16807&player=52523f26f5b23538f000001c

The params are accessible on the server in socket.handshake.query

socketio.listen(server).on('connection', function(socket) {
console.log('socket info = ', socket.handshake.query.player);
like image 83
Stan Avatar answered Oct 05 '22 20:10

Stan


I'm accessing the url like this:

io.on('connection', function(conn){
    console.log(conn.handshake.headers.referer);
});
like image 24
Jamie Popkin Avatar answered Oct 05 '22 20:10

Jamie Popkin