How To Use Axios with JavaScript
Practical axios tutorial: learn how to use Axios with JavaScript to make GET, POST, and DELETE requests (JSONPlaceholder demo), with async/await, error handling, and best practices.
Drake Nguyen
Founder · System Architect
Introduction
This axios tutorial demonstrates how to use Axios — a promise-based JavaScript HTTP client — to make API requests from the browser and Node.js. You’ll learn how to perform common axios http requests such as GET, POST, and DELETE using async/await, handle responses and errors, and wire results into a small todo-list UI that talks to the JSONPlaceholder API.
Prerequisites
Before you begin, make sure you have:
- Node.js and npm installed locally (any recent LTS version is fine).
- A code editor and a browser for testing the front-end.
We will install Axios (javascript http client) and use a simple bundler for development. The examples are compatible with axios node js and browser builds.
Step 1 — Project setup
Create a new folder for the sample app, initialize npm, and add Axios. You can also use a CDN in browser-only environments.
$ mkdir axios-js-tutorial
$ cd axios-js-tutorial
$ npm init -y
$ npm install axios
# optional: install a bundler for local development (e.g. parcel)
$ npm install --save-dev parcel-bundler
To avoid runtime issues when using async/await in some bundlers, add regenerator-runtime if needed and create an entry file named app.js. In the browser you can include Axios via CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Step 2 — GET request (axios get request example javascript)
Use Axios to fetch todos from JSONPlaceholder. The following example shows a small GET helper using async/await. This demonstrates axios get request example javascript and how the response object contains data, status, and headers.
// app.js (imports and base URL)
import 'regenerator-runtime/runtime';
import axios from 'axios';
const BASE_URL = 'https://jsonplaceholder.typicode.com';
export const getTodoItems = async () => {
try {
const response = await axios.get(`${BASE_URL}/todos?_limit=5`);
return response.data; // array of todos
} catch (err) {
console.error('GET error', err);
}
};
Render the results into the DOM by creating list items and appending them to an unordered list. This ties the axios get results to a simple UI so you can see the requests in action.
Step 3 — POST request (axios post request example javascript)
Add a form to capture a new todo and submit it to the API using a POST request. This is a typical axios post request example javascript using async/await.
// index.html (form snippet)
<div id="new-todos">
<h3>New Todo</h3>
<form>
<label>Title <input id="new-todos__title" type="text" /></label>
<button type="submit">Add</button>
</form>
</div>
// app.js (add + form handler)
export const addTodoItem = async (todo) => {
try {
const res = await axios.post(`${BASE_URL}/todos`, todo);
return res.data; // new todo from server
} catch (err) {
console.error('POST error', err);
}
};
// form event listener
const form = document.querySelector('form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const title = document.querySelector('#new-todos__title').value.trim();
if (!title) return;
const todo = { userId: 1, title, completed: false };
const created = await addTodoItem(todo);
// update list with created (UI helper)
});
JSONPlaceholder returns the created resource in the response body. Updating the page with that object completes the create flow.
Step 4 — DELETE request (axios delete request example javascript)
Wire each rendered todo item so clicking it removes the item locally and sends a DELETE request. This covers axios delete request example javascript.
export const deleteTodoItem = async (id) => {
try {
const res = await axios.delete(`${BASE_URL}/todos/${id}`);
return res.data;
} catch (err) {
console.error('DELETE error', err);
}
};
// remove element and call API
const removeTodoElement = async (event, element) => {
element.parentElement.removeChild(element);
const id = element.id;
await deleteTodoItem(id);
};
// create list item and bind onclick
const createTodoElement = (item) => {
const li = document.createElement('li');
li.id = item.id;
li.appendChild(document.createTextNode(item.title));
li.onclick = async (e) => await removeTodoElement(e, li);
return li;
};
After clicking an item the UI is updated immediately and the DELETE request is sent. For real backends, consider confirming deletion and handling failures so the UI stays in sync.
Error handling and advanced tips
Axios exposes a few useful features beyond the basics:
- Request configuration (headers, timeout): you can pass an options object to set Authorization headers, content-type, or a timeout (see axios headers authorization example and axios request timeout example).
- Create an instance with defaults: use
axios.create({ baseURL, timeout })to centralize settings (axios create instance baseURL example). - Interceptors: attach request/response interceptors to add tokens or handle global errors.
- Promises: Axios returns promises, so you can use .then/.catch or async/await (axios promise).
Comparison and best practices
Compared to the native fetch API, Axios provides automatic JSON transforms, a simpler response structure, and convenience helpers for request cancellation and interceptors. For lightweight cases, fetch may be enough, but axios javascript shines when you need a full-featured javascript http client.
When building production applications, follow these recommendations:
- Centralize API logic in modules or services (use axios.create to set baseURL and headers).
- Handle network errors and show friendly messages to users (axios error handling try catch).
- Set reasonable timeouts and retry strategies where appropriate.
- Sanitize and validate data before sending it to APIs.
Conclusion
This axios tutorial covered how to perform GET, POST, and DELETE requests with Axios in a small todo example, including async/await usage, basic error handling, and pointers to advanced features such as interceptors and instances. Try extending the sample with headers for authorization, request timeouts, or by swapping a different API to practice axios jsonplaceholder example variations.
Further reading: explore guides on integrating Axios with frameworks (React, Vue) and compare fetch vs axios for your specific use case.