7

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".

3 Answers 3

4

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);
2

I'm accessing the url like this:

io.on('connection', function(conn){
    console.log(conn.handshake.headers.referer);
});
1

Use the URL api. http://nodejs.org/docs/latest/api/url.html

u = url.parse(url)
console.log(u.path)
3
  • but au do I get the string I can parse?
    – poppel
    Commented Mar 26, 2013 at 13:22
  • @poppel oh! sorry, I didn't realize you didn't have that informtion. You can always get the URL using window.location on the client side, and pass that information along with your data.
    – Munim
    Commented Mar 26, 2013 at 13:34
  • Just going to note that trusting the page to send the correct address is very bad. If you had some sort of room system or authentication system that relied on you being at a specific url, a user could just spoof it and gain access to other places. Commented Feb 12, 2016 at 11:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.