【问题标题】:How to call axios from other folder如何从其他文件夹调用axios
【发布时间】:2021-11-27 06:50:23
【问题描述】:

我想在该文件夹中创建新文件夹名称 services 将包括所有 axios 操作,我在这里使用 vue。这是我尝试的..

我的保存功能

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

我的服务文件

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

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

我的插件文件

import axios from "axios";

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

但是当我尝试时,我得到了一个错误

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

【问题讨论】:

    标签: javascript node.js vue.js axios


    【解决方案1】:

    好吧,您已经将axios 定义为() => import("../plugins/axios");,所以它是一个函数,它没有.get 方法。此外,将 import 作为函数使用会使其返回一个 Promise。你需要做的:

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

    【讨论】:

    • 嗨,感谢您的回答,但我仍然遇到同样的错误
    • 试试const axios = import('../plugins/axios').defaultimport axios from '../plugins/axios'
    • 使用default 我得到Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'get') 如果使用第二个exports is not defined
    • 哦,就是这样 - 我忘了,当你使用 import 作为函数时,它会返回一个承诺。我会更新答案
    • 我收到了这个_context.sent.get is not a function
    【解决方案2】:

    我解决了这个问题

    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(() => {});
    };
    

    所以,改为从plugins 文件夹导入axios,直接从services 使用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-01
      • 2016-02-28
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      相关资源
      最近更新 更多