Customize your Vue 3 application with custom Axios functions for handling GET, PUT,

I am looking to enhance my use of axios by customizing the get, post, and put functions. After performing the axios.create() operation, I want every subsequent get operation to include a then and catch block.

import axios from "axios";

export default (apiName = "") => {
    let headers = {
        "Content-Type": "application/json"
    };

    let token = JSON.parse(localStorage.getItem("token") || "{}");

    if (token && token !== "") {
        headers.Authorization = `Bearer ${token.AccessToken}`;
    }
    const instance = axios.create({
        baseURL:
            apiName === ""
                ? process.env.VUE_APP_API_URL
                : process.env.VUE_APP_API_URL + apiName,
        withCredentials: false,
        headers: headers
    });
    return instance;
};

axios.post('/api/Export/CopyShippingPlan/', plan)
            .then(handleResponse)
            .catch((error) => {
                console.log(error);
            });

I aim to streamline the process by defining axios.post directly after axios.create, allowing for the inclusion of a then and catch action wherever axios.post is called. This eliminates the need to manually add then and catch blocks each time axios is used.

Answer №1

If you're searching for a way to manage HTTP requests effectively, consider using interceptors:

  • The response interceptor is triggered after every axios response
  • The request interceptor runs before every axios request

For instance:

const ApiService = axios.create()

ApiService.interceptors.response.use(
    config => {
        //your custom code

        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    })


ApiService.interceptors.request.use(
    config => {
        //your custom code
        
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    })

Once configured, simply use axios.get, axios.post, etc., without any extra steps.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Event handler assigned to a group of constantly changing elements

Here is my JavaScript code: $(document).ready(function(){ $('#data1').change(function(){ title = $('#title1').val(); url = $('#url1').val(); $.post('library/edit.php',{title:title, url:ur ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

Problem with BeforeRouteEnter causing failure to populate data in variable

After setting up a web API that successfully sends data, I encountered an issue with my Vuejs app's data table component. Even though I made an API call using Axios within the BeforeRouteEnter hook, the data from the response doesn't seem to save ...

Closing a Javascript Websocket connection may result in server crash

I encountered an issue while trying to exchange data between my client and server. It seems that every time I closed my client, the server crashed... My server runs on Node.JS using the nodejs-websocket library. After some investigation, I discovered tha ...

Special function to handle ajax requests malfunctioning

I am seeking to develop a unique function for AJAX post requests. Below is the existing source code: function handleAjax(url, data) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.st ...

Updating Bootstrap modal content based on button clickExplanation on how to dynamically change the content

I am looking to dynamically change the content displayed inside a modal based on the button that is clicked. For example, clicking button one will only show the div with the class 'one' while hiding the others. $('#exampleModalCenter&a ...

extracting data from json using javascript

Here is the data in JSON format var testData = {text: '{"status":200}'}; I am attempting to extract the status using this code: console.log(testData.text.status); However, it returns undefined Could you please provide guidance on how to succ ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

Display HTML content using AJAX within a div element

Within my HTML code, I have the following: <li class="register"><a href="">Registreer</a></li> as well as <div id="content"> </div> I attempted to load an HTML file into the div using the code below in the header se ...

From javascript to utilizing ajax calls to interact with php scripts,

I am currently working on a page called edit.php where I need to pass a JavaScript variable to a modal window containing PHP in order to execute a query and retrieve data. Unfortunately, my experience with Ajax is limited and I haven't been able to fi ...

Error: The function $scope.apply is invalid and cannot be executed

I am attempting to display the contacts list after retrieving it using rdflib.js. The data is being loaded and stored in the list within the scope. However, I am running into an issue where the $scope is not updating, and it appears that I may be calling ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...

I am experiencing an issue where my JSON array is only returning the last element. Any suggestions on how to

I am facing an issue with my JSON array and Ajax code. Here is the snippet of my code where I upload an Excel file, convert it to JSON, then save it as a string in my database: function exportExcelToTable() { $('#upload-excel-convert').chang ...

What is the best way to send a JSON object to bootstrap-table?

In my controller, I am passing a JSON encoded object to the view. Using a Bootstrap table in the view to display the data, but it is showing "No matching records found." Can someone please assist with this issue? Here is my controller: see image And here ...

Tips for ensuring math formulas display correctly in CKEditor

I'm currently struggling to properly display the correct format of a math formula in ckeditor. I have made numerous attempts to find a solution, but so far, none have been successful. Here is an excerpt of my code: <html> <head> <scr ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Is it possible to use an onclick function to input JavaScript values into a password entry box seamlessly?

Is there a way to input password values continuously using a JavaScript onclick function into a password field? I have two images, one 'Blue' and one 'Red', that trigger an onclick function with the following values: Blue= w3! Red= T4 ...

What is the method for displaying various page views on a single URL?

For instance: Let's say I have a URL like /content/supercontenturl/. If the content type is a video (defined in my database), I will display a video player on the page along with other components. However, if the content type is text or something else ...