Converting short URLs to long URLs can be a common task in web development, especially when dealing with redirects. In this post, we'll explore how to achieve this using JavaScript with two popular libraries: Axios and Fetch API. We'll demonstrate how to retrieve the full URL from a shortened TikTok link.
Using Axios
Axios is a promise-based HTTP client for the browser and Node.js. Below is a simple example of how to use Axios to convert a short URL to its long form.
axios("https://vt.tiktok.com/ZS6yXCpvq/")
.then(res => console.log(`Full URL with Axios: ${res.request.res.responseUrl}`))
.catch(err => console.error(err));
// Full URL with Axios: https://www.tiktok.com/@bigthink/video/7345607663322926366
Explanation:
- We initiate a GET request to the short URL using axios().
- Upon success, the response object contains a property res.request.res.responseUrl that holds the full URL after following any redirects.
- If there’s an error during the request, it will be caught in the catch block, and we log the error message.
Using Fetch
The Fetch API provides a more modern way to make network requests. Here’s how you can use it to achieve the same result:
fetch("https://vt.tiktok.com/ZS6yXCpvq/")
.then(res => console.log(`Full URL with Fetch: ${res.url}`))
.catch(err => console.error(err));
// Full URL with Fetch: https://www.tiktok.com/@bigthink/video/7345607663322926366
Explanation:
- The fetch() function initiates a request to the specified URL.
- The res.url property contains the final URL after any redirects.
- Similar to Axios, errors are handled in the catch block.
Conclusion
Both Axios and Fetch provide straightforward methods for converting short URLs to long URLs in JavaScript. While Axios may offer additional features like interceptors and automatic JSON data transformation, Fetch is built into modern browsers and is quite powerful for basic requests. Depending on your project requirements, you can choose either method for handling URL redirection.
Top comments (0)