javascript - How to get a url as a param in Node.js? -
code:
app.get("/:url", function(req,res) { var url = req.params.url; res.send(url); });
problem:
this not work.
if try:
http://localhost:3000/https://www.google.com
i get:
cannot /https://www.google.com
you can try this, using regex:
var app = require('express')(); app.get(/^\/(.*)/, function (req, res) { var url = req.params[0]; res.send(url); }); app.listen(3000, () => console.log('listening on 3000'));
when run:
curl http://localhost:3000/https://www.google.com
the server should return:
https://www.google.com
update
there controversy whether or not colons legal in urls.
see question details:
according rfc 3986 legal url:
http://localhost:3000/https://tools.ietf.org/html/rfc3986
but note while legal well:
http://localhost:3000/https://tools.ietf.org/html/rfc3986#section-3.3
if entered url in browser, server get:
/https://tools.ietf.org/html/rfc3986
in request. reason while not strictly necessary still recommend url-encoding url put in other urls - see answer zac delventhal.
experiment
using above code example, command:
curl http://localhost:3000/https://www.google.com/
will output this:
https://www.google.com/
but command:
curl 'http://localhost:3000/https://www.google.com/#fragment'
will output this:
https://www.google.com/
note used single quotes above not because necessary here - they're not, see this:
echo http://localhost:3000/https://www.google.com/#fragment
but show hash fragment doesn't disappear because treated comment shell in case thought that reason. not sent when quotes used, , happens can demonstrated -v
switch of curl
:
* connected localhost (127.0.0.1) port 3000 (#0) > /https://www.google.com/ http/1.1 > user-agent: curl/7.35.0 > host: localhost:3000 > accept: */*
as can see hash fragment not sent http impossible server know existed.
incidentally, demonstrates using un-encoded url within other urls not mess proxy, because http requests proxy servers send this:
get https://www.google.com/ http/1.1
and not this:
get /https://www.google.com/ http/1.1
so cannot confused. (note slash.)
Comments
Post a Comment