a guide to structuring REST API requests with axios in Vue.js

In my Vue.js app, I am utilizing Axios to consume a REST API. Each time I make an API call, I create a new instance of Axios with the necessary authentication headers by calling axios.get in various places.

// UserdataComponent.vue
const anInstance = axios.create({
  headers: {'X-API-TOKEN': store.state.token},
  auth: {
    username: SOME_USERNAME,
    password: SOME_PASSWORD
  }
})
anInstance.get(API_BASE_URL + '/userdata')

This process is repeated throughout my codebase whenever a REST API call is made.

To optimize and keep the code DRY (Don't Repeat Yourself), I decided to move the axios instance creation logic to a separate file.

I transferred the axios instance creation code to a separate file and attempted to export it as an object. This exported object could then be imported wherever needed for consuming the REST API.

// http.js
import axios from 'axios'
import store from 'store/store.js'

const HTTP = axios.create({
  baseURL: API_BASE_URL,
  headers: { 'X-API-TOKEN': store.state.token },
  auth: {
    username: SOME_USERNAME,
    password: SOME_PASSWORD
  }
})

export default HTTP


// UserdataComponent.vue
import HTTP from 'http.js'
...
HTTP.get('/userdata')

However, this approach resulted in errors, with axios.create being interpreted as a string rather than a callable function.

What adjustments should I make to achieve the desired outcome? Is this method of modularizing the HTTP request mechanism appropriate?

Answer №1

Perhaps this solution may address your query by showcasing a neat method of implementation.

If you opt to establish the axios instance in a distinct file, it becomes plausible to export specific API calls, thereby enabling accessibility for other components as well.

// api.js
const HTTP = axios.create({
  baseURL: API_BASE_URL,
  headers: { 'X-API-TOKEN': store.state.token },
  auth: {
    username: SOME_USERNAME,
    password: SOME_PASSWORD
  }
})

export default {
  getSomeData () {
    return HTTP.get('/endpoint')
  },
  postSomeData (id, name) {
    return HTTP.post('/endpoint', {
      id: id,
      name: name
    })
  }
}

Subsequently, within your component, import the api.js and leverage it in the following manner:

//component.vue
import myApi from '../path/to/api'

export default {
  name: 'myComponent',
  methods: {
    someMethod () {
      myApi.getSomeData().then((response) => {
        ...code
      })
    }
  }
}

Answer №2

If you're looking to streamline your requests, consider implementing axios interceptors:

Axios.interceptors.request.use((config) => {
  // Customize the config settings here..
  // Include credentials in every request.
  config.withCredentials = true
  config.timeout = 10000
  config.headers['Accept-Language'] = i18n.locale
  config.headers['Content-Type'] = 'application/json'
  return config
})

This snippet can be incorporated into your main file.

By leveraging this code, your credentials will automatically be attached to all requests, eliminating the need to duplicate the same code repeatedly...

To delve deeper into this topic, visit https://github.com/axios/axios#interceptors or explore related resources online.

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

What is the best way to replicate a VueJS project?

While attempting to replicate an entire VueJS project using cp -r project clone_project, I encountered this error upon executing npm run serve from the clone_project directory: > [email protected] serve /Users/path_to_clone_project/clone_project > v ...

Issues persist with the Angular UI Tree Module: the removed callback is not functioning as

I am currently utilizing a module that can be found at the following URL: https://github.com/angular-ui-tree/angular-ui-tree Unfortunately, I am facing an issue with getting the removed callback to work properly. The accept callback seems to be functionin ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Angular 2 404 Error persists despite successful retrieval of data from Oracle database using Backend Nodejs URL entered directly into the browser

Recently, I've been working on displaying data in my Angular frontend that is fetched from an Oracle DB connected to my Node backend. When I access the physical API link, the data appears and is displayed in the backend console.log. I'm wonderin ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

Change the order of numbering in ordered lists

I am seeking a way to change the ordering of an ordered list to be in descending order. You can view a live example here. Instead of having the counter span multiple ol elements, I would like the counter to reset after each ol. For the live demo, the des ...

Exploring Next.js: Advanced capabilities of shallow routing in combination with dynamic routes

Many people seem to be confused about the behavior of shallow routing with dynamic routes in Next.js. When attempting shallow routing, the page is refreshed and the shallow option is ignored. Let's consider a scenario where we start on the following ...

Can AngularJS filter be used with an array of strings for sorting?

Understanding how to implement an Angular filter to solve a problem I'm facing is proving to be quite challenging for me. Let's take a look at a simple example of my data structure, which consists of an array of tasks: var tasks = [ { Title ...

What is the best way to display data retrieved from a GET request in Angular?

Spending too much time on a development issue is causing me frustration. After extensive research, I find myself stuck at this point. The problem lies in making a GET request from a service which is called by a controller. Below is the code for the servi ...

Dismiss Bootstrap by clicking anywhere

I have a specific input that is displayed when clicked and disappears with the next click: <a href="#;" class="asset_info" data-asset_id="{{ asset.pk }}" data-toggle="focus" tabindex="0" data-placement="left" data-trigger="focus" >Hello</a> ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Issue: The content of the text does not align with the HTML generated by the server

I'm struggling with an algorithm in next.js and encountering hydration errors. Here is the code I am using: import numbers from "../../functions/numberGenerators.js" export default function test() { ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

The white-spaces in Quill JS do not retain their original formatting

I recently integrated Quill JS editor into my website. During testing, I noticed that any text inputted after a white space gets emitted when alerting the content. Below is the HTML code snippet: <div id="postCommentEditor" class="postCo ...

Using React Higher Order Components with several different components

Is it possible to create a React HOC that can accept two components instead of just one wrapped component and toggle between them? For instance, in the code snippet below, rather than having <h3>component one</h3> and <h3>component two< ...

I am receiving a reference error even though the day variable has already been defined. Can you kindly point out

When I attempt to log in, the page is giving me the correct output. Interestingly, even after encountering an error, the webpage continues to function properly. app.get("/", function(req, res) { let day = date.getDate(); console.log(day); r ...