【问题标题】:Nuxt fetch hook api can't access the api folderNuxt fetch hook api 无法访问 api 文件夹
【发布时间】:2021-07-04 23:44:19
【问题描述】:

我有一个我在fetch() 钩子中调用的 api:

pages/pageOne.vue:

  async fetch() {
    const { store, error } = this.$nuxt.context;
    try {
      await store.dispatch("folderOne/apiOne", null, { root: true });
    } catch (e) {
      error({
        message: "error"
      });
    }
  }

然后在我的商店中,我有这样的apiOne 操作设置:

store/folderOne/index.js:

//importing the api file here
const actions = {
   apiOne({ commit }) {
    apiFile.apiOne().then(data => {
        if(data && data.status === 200){
          // then commit
        }
      })
      .catch(error => {
        console.log(error);
      });
  },
}

然后我有一个用于我的 API 设置的文件,如下所示:

api/apiFile.js:

import axios from "axios";

const httpClient = axios.create({
  headers: {
    key: 'value
  }
});

const baseUrl = process.env.config.baseUrl;

export default {
  apiOne() {
    return httpClient.get(`${baseUrl}values);
  },
}

它不起作用。但是,当我在 @click 方法中调用相同的 apiOne 时,它会起作用。任何人都知道出了什么问题,我该如何解决?

【问题讨论】:

  • apiOne() 中登录 URL 时会看到什么?

标签: api vue.js plugins axios nuxt.js


【解决方案1】:

您的商店是并且应该是您的应用程序的全局构造。 这意味着当您要求采取行动并且您的设置正确时,您不必自己处理指令/文件夹。

在您的情况下,您应该做的就是像这样在组件中分派操作:

async fetch() {
    const { store, error } = this.$nuxt.context;
    try {
      await store.dispatch("apiOne", null, { root: true });
    } catch (e) {
      error({
        message: "error"
      });
    }
  }

【讨论】:

  • 如果这不起作用,请提供更多信息,例如您的商店配置等。
  • 谢谢,但 def 不是问题。 1-我有几个商店文件。 2-我可以调用api,如果我直接从商店调用api而不使用apiFile.js,它就可以工作,例如: const actions = { async apiOne({ commit }) { await axios .get( '${baseUrl} values', { headers: { key: "value" } } ).then() ...问题似乎是fetch()没有访问apiFile.js
猜你喜欢
  • 2021-12-28
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多