更改 axios 的默认基数 url

Change the default base url for axios

我已经这样配置了我的 axios

const axiosConfig = {
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 30000,
};

Vue.prototype.$axios = axios.create(axiosConfig)

在我的组件中,我调用了

this.$axios.get('items').then()..

现在上面的工作正常,但我想在不影响全局基础 URL 的情况下更改 baseURL 以便在我的组件中我可以在没有 API 端点的情况下简单地使用它所以

我试过了

this.$axios.baseURL = "http://127.0.0.1:8000";
this.$axios.get().. //this is still in api endpoint

我该怎么做?

而不是

this.$axios.get('items')

使用

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

如果你不通过 method: 'XXX' 那么默认情况下,它将通过 get 方法发送。

请求配置: https://github.com/axios/axios#request-config

把我的两分钱放在这里。我想在不针对我的特定请求对 URL 进行硬编码的情况下执行相同的操作。所以我想出了这个解决方案。

要将 'api' 附加到我的基数 URL,我将我的默认基数 URL 设置为,

axios.defaults.baseURL = '/api/';

然后在我的具体要求中,在显式设置方法和url之后,我将baseURL设置为'/'

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });

axios docs 你有 baseURLurl

baseURL 将在发出请求时添加到 url 之前。因此,您可以将 baseURL 定义为 http://127.0.0.1:8000 并向 /url

发出请求
 // `url` is the server URL that will be used for the request
 url: '/user',

 // `baseURL` will be prepended to `url` unless `url` is absolute.
 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
 // to methods of that instance.
 baseURL: 'https://some-domain.com/api/',

  1. 创建 .env.development, .env.production 文件(如果不存在)并添加你的 API端点,例如:VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
  2. 在 main.js 文件中,在导入后添加此行:axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT

就是这样。 Axios 默认基础 Url 替换为特定于构建模式的 API 端点。 如果您需要针对特定​​请求的特定 baseURL,请这样做:

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

你也可以用这个 (对于 nuxt 和 vue)

this.$axios.defaults.baseURL = 'http://example.com/example'

这对我来说适用于一个请求的自定义 baseURL

async getDataFromServer({ commit }, payload) {
    commit('setLoadingStatus', true)
    try {
      const page = payload.page || 1
      const sort = payload.sort || 'published_at'

      this.$axios.defaults.baseURL = 'http://example.com/example'
     
      const { data } = await this.$axios.get(`/example`)

      commit('setItOnState', data)
    } catch (e) {
      throw new Error(e)
    } finally {
      commit('setLoadingStatus', false)
    }
  },

如果其他人仍然需要帮助:

你可以直接在你想用的地方改Axios baseURL

anotherAxiosRequest(){
 axios.defaults.baseURL = http://wwww.example.com
 axios({
   url:'/cats' //=>  http://wwww.example.com/cats
 })
}

它会改变基数 URL

请注意,这不会更改 main.js

中定义的基数 URL