Home > Net >  Configure Axios as reusable module
Configure Axios as reusable module

Time:06-09

I want to create a axios config file where I can create several apis with different configurations, e.g. http.js:

import axios from "axios";

const backendApi =  axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL   "api/",
});

const anotherApi =  axios.create({
  baseURL: "https://example.com",
});

export default {
  backendApi,
  anotherApi
};

Now I want to use the backendApi, e.g. in my actions.js:

import backendApi from "@/http"

const userRegister = (context, user) => {

  backendApi
    .post("users/register", user)
    .then((resp) => {
      //
    })
    .catch((err) => {
      //
    })
}

export default {
  userRegister
}

But I receive the following error:

Error in v-on handler: "TypeError: http__WEBPACK_IMPORTED_MODULE_0_.default.post is not a function"

CodePudding user response:

You are not using exports the way you intend to.

What you want is named exports instead of a default one.

import axios from "axios";

export const backendApi =  axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL   "api/",
});

export const anotherApi =  axios.create({
  baseURL: "https://example.com",
});
import { backendApi } from "@/http"

export const userRegister = (context, user) => {
  backendApi
    .post("users/register", user)
    .then((resp) => {
      //
    })
    .catch((err) => {
      //
    })
}
  • Related