programing

Axi의 기본 기본 URL 변경

goodcopy 2022. 8. 11. 23:53
반응형

Axi의 기본 기본 URL 변경

나는 나의 공리를 다음과 같이 구성했다.

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

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

내 컴포넌트 안에서 나는 콜을 발신한다.

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

위의 할 수 , 는 이 내용을 변경하고 싶습니다.baseURL을 주지 않고 할 수 컴포넌트 없이 사용할 수 있습니다.

해봤어요

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을 한 후 URL을 합니다.에서 URL로'/'

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });
  1. .env.development, .env.production 파일이 없는 경우 만들고 API 엔드포인트를 추가합니다.다음은 예를 제시하겠습니다.VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
  2. Import 행을 추가합니다.main.js 일 import import Import 음음 。axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT

그리고 이것이 마지막입니다.Axios 기본 기본 URL이 빌드 모드별 API 끝점으로 대체되었습니다.특정 베이스가 필요한 경우특정 요청에 대한 URL은 다음과 같이 수행합니다.

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

다른 사용자가 아직 도움이 필요한 경우:

Axios 기본 URL을 사용하려는 곳에서 직접 변경할 수 있습니다.

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

그러면 기본 URL이 변경됩니다.

main.js에서 정의된 기본 URL은 변경되지 않습니다.

Axios 문서에서 기본 제공URLURL

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/',

nuxt 및 vue에도 사용할 수 있습니다.

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

이것은 커스텀 베이스에서 나에게 효과가 있었다.1개의 요구에 대한 URL

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)
    }
  },

언급URL : https://stackoverflow.com/questions/47407564/change-the-default-base-url-for-axios

반응형