I feel like pulling my hair out; this is either super simple and i'm having brain freeze or it is not that simple.
What I want
I am trying to unshorten a shortened URL using firebase, when a user goes to:
myapp.firebaseappurl.com/url/SHORTENEDLINK
SO wont let me add a shortened URL
I would like the output to be:
{
"url": "https://stackoverflow.com/questions/45420989/sphinx-search-how-to-use-an-empty-before-match-and-after-match"
}
What I have tried
firebase.json
file:
{
"hosting": {
"public": "public",
"rewrites": [ {
"source": "/url/:item",
"destination": "/url/:item"
} ]
}
}
index.js
file:
const functions = require('firebase-functions');
exports.url = functions.https.onRequest((requested, response) => {
var uri = requested.url;
request({
uri: uri,
followRedirect: true
},
function(err, httpResponse) {
if (err) {
return console.error(err);
}
response.send(httpResponse.headers.location || uri);
}
);
});
Result
When I go to myapp.firebaseappurl.com/url/SHORTENEDLINK
I get the following:
Error: could not handle the request
You are seeing
Error: could not handle the request
since there probably was an exception and it timed out.Check your logs using:
Refer docs for more details
Here's how I got URL unshortening to work
You can follow the hello world example straight away and use the above code as your
function
.Above code uses
HEAD
requests to peek into 'Location` field of the headers and decides if the url can be further unshortened.This is lighter as HEAD requests ask for no body (thereby avoiding body parsing). Also, no third party lib required!
Also note that the url passed as a query param. So the request would be
Saves you the trouble of URL re-writes. Plus semantically makes a little more sense.
I think your code is fine. What you're doing incorrectly is that you're using Express-js notations in your
firebase.json
'srewrites
node. (the:item
part). These don't work in the Firebase Realtime Database.So, instead of doing that, change your
firebase.json
to the following :-This is also the advocated approach in the Cloud Functions for Firebase's URL Shortener sample.
First make sure you are receiving the request properly with the shortened url.
Now when you visit myapp.firebaseappurl.com/url/SHORTENEDLINK you should see the SHORTENEDLINK in plain text. When that's working, try the redirect.
Also it's good practice to
npm install
with--save
so they end up in thepackages.json
. While firebase copies your node_modules folder, most other SaaS platforms runnpm install
.Did you tried using
{ source: '/url/**' }
syntax?You can use something like this;
and then you can parse the url from the request.