fetch
The fetch() API in JavaScript provides a modern and flexible interface for making network requests, primarily designed to replace the older XMLHttpRequest. It allows you to fetch resources like JSON data, HTML, images, and more from a server.
Basic Syntax
fetch(url, options)
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle any errors
});
Parameters
url: The URL to which the request is sent.
options (optional): An object that allows you to configure the request (method, headers, body, etc.).
Key Points
fetch returns a Promise.
It won’t reject on HTTP errors like 404 or 500 — you have to check response.ok.
Example:
function getWeather() {
const apiKey = "2a50fd8aa879e6af857307fdc1a16bc6";
const url = `http://api.openweathermap.org/data/2.5/ weather?q=${city}&appid=${apiKey}&units=metric`;
fetch(url)
.then((res) => {
return res.json();
}).then((data) => {
console.log(data.main.feels_like);
result.innerHTML = `Temperature : ${data.main.temp}`
}).catch((error) => {
console.log(error);
async:
A function declared with async always returns a Promise.
async function getData() {
return "Hello";
}
Calling getData() returns a Promise that resolves to "Hello".
await:
You use await inside async functions to pause the code until a Promise is resolved.
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
Axios:
Axios is a promise-based HTTP client for browsers and Node.js. It simplifies making requests to APIs and handling responses.
Installing Axios:
Use npm or yarn:
npm install axios
Or use a CDN in your HTML:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Or with async/await:
async function fetchPosts() {
try {
const res = await axios.get('https://api.example.com/posts');
console.log(res.data);
} catch (err) {
console.error('Axios error:', err);
}
}