Vue 스터디

Nuxt.js에서 Axios 통신

옹재 2021. 6. 24. 11:26
728x90
반응형

Nuxt.js에서 Axios 통신

설치

프로젝트에 @nuxtjs/axios 종속성을 추가합니다.

yarn add @nuxtjs/axios

그 다음 nuxt.config.js 의 module 섹션에 추가해줍니다.

export default{
    ...
    modules : ['@nuxtjs/axios'],
    ...
}

이렇게 하면 nuxt 앱에서 $axios를 사용할 수 있습니다. 위 과정도 귀찮다면 yarn create nuxt-app 으로 프로젝트를 생성할 때 axios를 추가해서 생성해주면 자동으로 의존성처리를 해줍니다.

옵션

export default {
  axios: {
    // Axios options here
  }
}

위 코드처럼 nuxt.config.js 파일의 axios 섹션 안에 옵션을 추가할 수 있습니다.

RuntimeConfig

RuntimeConfig의 사용은 환경 변수를 사용하는 케이스에서 필수입니다. 사용하지 않는다면 변수들이 빌드되는 동안 하드코딩되거나 변경되지 않는다고 합니다.

export default {
  modules: [
    '@nuxtjs/axios'
  ],

  axios: {
    baseURL: 'http://localhost:4000', // Used as fallback if no runtime config is provided
    //this.$axios.defaults.baseURL 로 접근 가능 
  },

  publicRuntimeConfig: {
    axios: {
      browserBaseURL: process.env.BROWSER_BASE_URL
    }
  },

  privateRuntimeConfig: {
    axios: {
      baseURL: process.env.BASE_URL
    }
  },

axios 확장

interceptor 추가해서 axios를 커스터마이징 하거나 global confilg를 바꾸고 싶다면 plugins를 사용하면 됩니다.

plugins 폴더에 추가할 인터셉터 파일을 생성해줍니다.

// plugins/axios.js
export default function ({ $axios, redirect }) {
  $axios.onRequest(config => {
    console.log('Making request to ' + config.url)
  })

  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/400')
    }
  })
}

생성해준 파일을 nuxt.config.js 의 plugins에 추가해줍니다.

export default {
  plugins: [
    '~/plugins/axios'
  ]
}

Axios 플러그인은 다음과 같은 helper들을 제공합니다.

  • onRequest
  • onResponse
  • onError
  • onRequestError
  • onReponseError

위의 함수들은 기본적으로 어떤 것도 리턴하지 않습니다. 아래와 같이 사용해서 쉽게 커스텀할 수 있습니다.

export default function ({ $axios, redirect }) {
  $axios.onError(error => {
    if(error.response.status === 500) {
      redirect('/sorry')
    }
  })
}

setBaseURL

baseURL을 쉽게 바꿀 수 있는 helper 함수를 제공합니다. 동적 런타임 url이 필요할 때 사용하면 좋습니다.

// Set baseURL (both client and server)
this.$axios.setBaseURL('http://api.example.com')

// Change URL only for client
if (process.client) {
  this.$axios.setBaseURL('http://api.example.com')
}

// Change URL only for server
if (process.server) {
  this.$axios.setBaseURL('http://api.example.com')
}

setHeader

말그대로 axios 통신에 전역으로 header 값을 지정해주는 함수입니다.

// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')

// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')

// Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
  'post'
])

// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])

setToken

토큰을 추가해주는 함수입니다.

// Adds header: `Authorization: 123` to all requests
this.$axios.setToken('123')

// Overrides `Authorization` header with new value
this.$axios.setToken('456')

// Adds header: `Authorization: Bearer 123` to all requests
this.$axios.setToken('123', 'Bearer')

// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])

// Removes default Authorization header from `common` scope (all requests)
this.$axios.setToken(false)
728x90
반응형