Home > Blockchain >  How to call axios from other folder
How to call axios from other folder

Time:10-07

I want to create new folder name services in that folder will include all axios action and I'm using vue here. Heres what I try..

my save function

save() {
  const CaseController = require("../services/gantt");
  CaseController.create(this.data);
},

my service file

const axios = () => import("../plugins/axios");

exports.create = async () => {
  return axios
    .get("/")
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {});
};

my plugins file

import axios from "axios";

export default axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  headers: {
    "Content-Type": "application/json",
  },
});

but when I try, I got an error

Uncaught (in promise) TypeError: axios.get is not a function

CodePudding user response:

Well, you've defined axios as () => import("../plugins/axios");, so it's a function, which does not have a .get method. Further, using import as a function makes it return a promise. You need to do:

const axios = import("../plugins/axios");

exports.create = async () => {
  return (await axios)
    .get("/")
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {});
};

CodePudding user response:

i solve this with

const axios = require("axios");
const instance = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  headers: {
    "Content-Type": "application/json",
  },
});

exports.create = async () => {
  instance
    .get("/")
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {});
};

so, instead import the axios from plugins folder, use it directly from services

  • Related