7

How do I send URL with hash to nodejs?

When I try to send a URL with hash in it, it doesn't work, but with ? it works.

const url = require('url');
const qs = require('querystring');
const http = require('http');
    
http.createServer(server).listen(1337, 'hostname');

function server(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write(req.url);
    
    var currentURL = url.parse(req.url, true);
    console.log(currentURL);
    res.end('\nHello World\n');
}
    
console.log('Server running at http://127.0.0.1:1337/');

Use case: Facebook access_token URL format is something similar to above

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Raxit Sheth
  • 2,491
  • 5
  • 17
  • 20
  • 2
    When you request a URL like this http://host:1337/#A=1111111 it's only sending this to the server http://host:1337/ and this fragment to the browser #A=1111111 Facebook fetches this URL locally in the browser, parses it and changes it to a get variable like this http://host:1337/?A=11111111 Then requests for the data using AJAX, parses all data, and writes it into the browser. This is an old technique which requires the 'onhashchange' event, currently, the best way to do this is by implementing pushState and changing the whole URL without refreshing the page. – neojp Jul 26 '12 at 21:22

1 Answers1

22

The part of the URL after the '#' mark, called the fragment, is not sent to the server. If you store data in the fragment, then it is up to you to process that data and do an ajax request with the data in a GET argument.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 2
    Facebook is calling back with that format to dev server using http://servername:port/path#access_token=somestring – Raxit Sheth Apr 02 '12 at 05:02
  • I really wish they didn't close this question. This facebook fragment is really annoying. – Gavin Jun 20 '14 at 00:25
  • I think this is part of OAuth2, and not specific to Facebook. And I suspect it is intentionally done this way so it's not used in more automated server-side authentication flows. – Marc Stober Jul 24 '23 at 12:41