Unshortening a url using Axios?

Viewed 822

I was reading how to unshorten a url with request in this article https://loige.co/unshorten-expand-short-urls-with-node-js/ and I wanted to know if it can be done in axios.

My Attempt:

 const geturl = async link => {
    const res = await axios({
      method: "get",
      url: link,
      maxRedirects: 1
    });
    console.log(res.headers.Location);
  };
geturl("URL GOES HERE");

Far as I can see, Axios does not use headers location like request does...

1 Answers

You can set maxRedirects to 0 then the redirection will be considered as an error and you'll be able to retrieve the Location header:

const geturl = async link => {
    try {
        return await axios({
            method: "get",
            url: link,
            maxRedirects: 0
        });
    } catch (e) {
        if (Math.trunc(e.response.status / 100) === 3) {
            console.log(e.response.headers.location);
            return geturl(e.response.headers.location);
        } else {
            throw e;
        }
    }
};

geturl("http://google.com").then(x => x.status).then(console.log);
Related