Home >Web Front-end >JS Tutorial >How to Convert Short URLs to Long URLs in JavaScript Using Axios or Fetch
Converting short URLs to long URLs is a common task in web development, especially when dealing with redirects. This article will explore how to achieve this using JavaScript and two popular libraries, Axios and the Fetch API. We will demonstrate how to retrieve the full URL from a shortened TikTok link.
Axios is a Promise-based HTTP client for browsers and Node.js. Below is a simple example of how to use Axios to convert a short URL into a long format.
<code class="language-javascript">axios("https://vt.tiktok.com/ZS6yXCpvq/") .then(res => console.log(`Axios获取的完整URL: ${res.request.res.responseUrl}`)) .catch(err => console.error(err));</code>
// Complete URL obtained by Axios: https://www.php.cn/link/99ec8b626a47132c52969dd081cdd808
Instructions:
Fetch API provides a more modern way of making network requests. Here's how to use it to get the same results:
<code class="language-javascript">fetch("https://vt.tiktok.com/ZS6yXCpvq/") .then(res => res.text()) .then(data => console.log(`Fetch获取的完整URL: ${data}`)) .catch(err => console.error(err)); </code>
// Complete URL obtained by Fetch: https://www.php.cn/link/99ec8b626a47132c52969dd081cdd808
Instructions:
Axios and Fetch both provide easy ways to convert short URLs into long URLs in JavaScript. While Axios may offer additional features like interceptors and automatic JSON data conversion, Fetch is built into modern browsers and is powerful for basic requests. Depending on your project needs, you can choose either method to handle URL redirects.
The above is the detailed content of How to Convert Short URLs to Long URLs in JavaScript Using Axios or Fetch. For more information, please follow other related articles on the PHP Chinese website!