Go Back

Handling HTTP Requests with Axios in JavaScript

11/06/20232 min read

Setting Up a Custom Axios Instance

import axios from 'axios' // Create a custom Axios instance const instance = axios.create({ baseURL: 'http://localhost:3000', }) export default instance

Performing a GET Request

const getSomeData = async () => { try { const response = await instance.get('/tasks') return response.data } catch (error) { console.error(error) } }

Performing a POST Request

const postSomeData = async (objParam) => { try { const response = await instance.post('/tasks', objParam) return response.data } catch (error) { console.error(error) } }

Performing a PATCH Request

const patchSomeData = async (id, objParam) => { try { const response = await instance.patch(`/tasks/${id}`, objParam) return response.data } catch (error) { console.error(error) } }

Performing a PUT Request

const putSomeData = async (id, objParam) => { try { const response = await instance.put(`/tasks/${id}`, objParam) return response.data } catch (error) { console.error(error) } }

Performing a DELETE Request

const deleteSomeData = async (id) => { try { const response = await instance.delete(`/tasks/${id}`) return response.data } catch (error) { console.error(error) } }

Usages

const executeRequests = async () => { const data = await getSomeData() console.log(data) const postData = await postSomeData({ title: 'New Task', completed: false }) console.log(postData) const patchData = await patchSomeData(1, { completed: true }) console.log(patchData) const putData = await putSomeData(1, { title: 'Updated Task', completed: true }) console.log(putData) const deleteData = await deleteSomeData(1) console.log(deleteData) } // Execute all requests executeRequests()