JS (browser and Node.js) provides built-in fetch function.
async function getData() {
const url = "given URL";
const queryURL = new URL("given route", url);
queryURL.searchParams.append("par1", val1);
queryURL.searchParams.append("par2", val2);
queryURL.searchParams.append("par3", val3);
const url = queryURL.href;
let result;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
result = await response.json();
console.log(result);
} catch (error) {
console.error(error.message);
}
return result;
}async function getData() {
const url = "given URL";
const queryURL = new URL("given route", url);
queryURL.searchParams.append("par1", val1);
queryURL.searchParams.append("par2", val2);
queryURL.searchParams.append("par3", val3);
const url = queryURL.href;
let result;
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
result = await response.json();
} catch (error) {
console.error(error.message);
}
return result;
}Axios is a wrapper around fetch, offering advanced features.
To install:
npm install axiosupfetch is a fetch client builder with schema validation. It can be a replacement for axios
To install:
npm i up-fetchimport axios from "axios";
// Make a request for a user with a given ID
axios
.get("given URL/?par1=val1")
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
// Optionally the request above could also be done as
axios
.get("given URL", {
params: {
par1: val1,
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get("given URL");
console.log(response);
} catch (error) {
console.error(error);
}
}axios
.post("given URL", formData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});import { useEffect, useState } from "react";
import { up } from "up-fetch";
const upfetch = up(fetch);
function App() {
const [results, setResults] = useState([]);
useEffect(() => {
let ignore = false;
async function loadData() {
const data = await upfetch("https://jsonplaceholder.typicode.com/users");
if (!ignore) {
setResults(data);
}
}
loadData();
return () => {
ignore = true;
};
}, []);
return (
<div style={{ display: "flex", flexDirection: "column" }}>
{results.map((s: { name: string }, i) => {
return <div key={i}>{s.name}</div>;
})}
</div>
);
}
export default App;import { up, isValidationError } from "up-fetch";
import { z } from "zod";
const upfetch = up(fetch, () => ({
onRequest: (options) => {
// Called before the request is made, options might be mutated here
},
onSuccess: (data, options) => {
// Called when the request successfully completes
},
onError: (error, options) => {
// Called when the request fails
},
}));
try {
const data = await upfetch(
// These parameters are set for this individual upfetch
// To set the parameters for all upfetch instances, move them
// to `up()` function's callback definition.
"given URL",
{
attempts: 3,
timeout: 30000, // request timeout
delay: 1000, // delay between each attempt
method: "POST",
body: formData,
params: {
par1: val1,
par2: val2,
par3: val3,
},
schema: z.object({
id: z.number(),
//...
}),
}
);
} catch (error) {
if (isValidationError(error)) {
console.log(error.issues);
}
}