简体   繁体   English

无法在 nuxt 中使用 axios 插件

[英]Unable to use an axios plugin in nuxt

I'm attempting to add an Axios plugin to Nuxt as described here , but it doesn't seem to work.我正在尝试按照此处所述向 Nuxt 添加 Axios 插件,但它似乎不起作用。

This is my plugins/axios.js file...这是我的plugins/axios.js文件...

export default function({ $axios }) {
  console.log('Im in the axios plugin')
  $axios.defaults.baseURL = `https://localhost:5001/api`
  $axios.defaults.headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
  $axios.onRequest((config) => {
    console.log('Making request to ' + config.url)
  })
}

This is my nuxt.config.js这是我的nuxt.config.js

plugins: ['~/plugins/axios'],
modules: ['@nuxtjs/axios']

And this is where I use Axios in a file called services/BookService.js :这是我在名为services/BookService.js的文件中使用 Axios 的地方:

import axios from 'axios'

export default {
  getBooks() {
    return axios.get('/Home')
  },
  getBooksFiltered(payload) {
    return axios.post('/Home/Filters', payload)
  }
}

I get the console.log('Im in the axios plugin') from within my plugin, but nothing else.我从我的插件中得到了console.log('Im in the axios plugin') ,但没有别的。 $axios.onRequest doesn't appear to run, and the baseURL doesn't appear to be set correctly when getBooksFiltered is triggered. $axios.onRequest不会出现运行,并且baseURL时不会出现正确设置getBooksFiltered被触发。 I get a 404 when it tried to hit the address http://localhost:3000/Home/Filters .当它尝试访问地址http://localhost:3000/Home/Filters时,我得到了404 As described in my plugin, the address should be https://localhost:5001/api/Home/Filters如我的插件中所述,地址应为https://localhost:5001/api/Home/Filters

I've also tried the following in my nuxt.config.js , but it doesn't work:我也在我的nuxt.config.js尝试了以下nuxt.config.js ,但它不起作用:

axios: {
  baseURL: 'https://localhost:5001/api'
}

Any ideas?有任何想法吗?

Edit编辑

I've modified my services/BookService.js based on the suggestion below to the following...我已经根据以下建议修改了我的services/BookService.js ...

export default {
  getBooks(axios) {
    console.log('Im in getBooks')
    return axios.get('/Home')
  }
}

My action request that makes my api call is the following....我的 api 调用的操作请求如下....

import BookService from '~/services/BookService.js'

export const fetchBooks = (context) => {
  console.log('Im in fetchBooks action')
  return BookService.getBooks(this.$axios)
    .then((response) => {
      context.commit('SET_BOOKS', response.data.booksList)
    })
    .catch((error) => {
      console.log(error)
    })
}

And my method in my component that calls the actions...我的组件中调用操作的方法......

async fetch({ store, error }) {
  try {
    console.log('Im in index -> fetch')
    await store.dispatch('fetchBooks')
  } catch (e) {
    error({
      statusCode: 503,
      message: 'Unable to fetch books at this time'
    })
  }
}

I'm aware that I may be mixing async/await with promises incorrectly but I don't believe it's the cause of this issue.我知道我可能错误地将 async/await 与 promise 混合在一起,但我不认为这是导致此问题的原因。

Console returns the following...控制台返回以下...

在此处输入图片说明

My network tab contains a single request to http://localhost:3000/ which seems incorrect.我的网络选项卡包含对http://localhost:3000/的单个请求,这似乎不正确。 It should be https://localhost:5001/api/Home based on the plugin and the address specified in the action.根据插件和操作中指定的地址,它应该是https://localhost:5001/api/Home It is also never entering $axios.onRequest它也永远不会进入$axios.onRequest

在此处输入图片说明

The axios-module sets up an Axios instance on the Nuxt app instance. axios-module在 Nuxt 应用实例上设置一个 Axios 实例。 When you import Axios from axios , and use it directly, you're not using the previously setup Axios instance.当您从axios导入 Axios 并直接使用它时,您没有使用之前设置的 Axios 实例。

To fix the issue, you could either reference the preconfigured Axios instance from window.$nuxt.$axios (only in the browser), or setup your service to take an Axios instance as a parameter:要解决此问题,您可以从window.$nuxt.$axios引用预配置的 Axios 实例(仅在浏览器中),或者设置您的服务以将 Axios 实例作为参数:

// services/BookService.js
export default axios => ({
  getBooks() {
    return axios.get('/Home')
  },
  getBooksFiltered(payload) {
    return axios.post('/Home/Filters', payload)
  }
})

// store.js
import BookService from '~/services/BookService.js'

export default {
  actions: {
    async getBooks({ commit }) {
      const books = await new BookService(this.$axios).getBooks()
      commit('SET_BOOKS', books)
    }
  }
}

Another solution from nuxt-community/axios-module #28 :来自nuxt-community/axios-module #28 的另一个解决方案:

~/plugins/axios-port.js ~/plugins/axios-port.js

 import { setClient } from '~/services/apiClient' export default ({ app, store }) => { setClient(app.$axios) }

~/services/apiClient.js ~/services/apiClient.js

 let client export function setClient (newclient) { client = newclient } // Request helpers const reqMethods = [ 'request', 'delete', 'get', 'head', 'options', // url, config 'post', 'put', 'patch' // url, data, config ] let service = {} reqMethods.forEach((method) => { service[method] = function () { if (!client) throw new Error('apiClient not installed') return client[method].apply(null, arguments) } }) export default service

Use:用:

 import apiClient from '~/services/apiClient' export default { async current () { return apiClient.get('...') } }

In my case I exported a customized axios instance as the doc suggested in my axios.js在我的情况下,我按照 axios.js 中的文档建议导出了一个自定义的 axios 实例

export default function ({ $axios }, inject) {
    const api = $axios.create({
        baseURL:'/api'
    })
    // Inject to context as $api
    inject('api', api)
  }

Then use this.$api.get or this.$api.post in your getBook service The above one works for me然后在你的 getBook 服务中使用 this.$api.get 或 this.$api.post 上面的一个对我有用

It seems you need to yarn add @nuxtjs/axios or npm install @nuxtjs/axios like the setup instruction here before it can work: https://axios.nuxtjs.org/setup似乎您需要像这里的安装说明一样通过yarn add @nuxtjs/axiosnpm install @nuxtjs/axios才能工作: https : npm install @nuxtjs/axios

I haven't experienced with nuxt yet but I don't think by adding some line of code into some js file without actually installing will make the package available into your repo.我还没有体验过 nuxt,但我不认为通过将一些代码行添加到某些 js 文件中而不实际安装会使该软件包可用于您的存储库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM