Nuxt.js - nuxt/axios (will continue to improve)


insert image description here

nuxt2

official document

Base

  • Download, create a new project, or an existing project, we can add the package through yarn (or npm)
    yarn add @nuxtjs/axios
    
  • nuxt.config.js configuration
    module.exports = {
          
          
      module:['@nuxtjs/axios'],  // 可以让我们全局使用 $axios
      axios:{
          
           
      	// 可以在这里做一些配置代理什么的
      },
      plugins: ['~/plugins/axios'],   //这个会对应咱们下面为axios写的插件
    }
    

add interceptor

Here we need to use plugins, that is, plugins
/plugins/axios.js . We need to create this file as our plugin to process axios

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

Here axios plugin provides some plugins

  • onRequest(config)

  • onResponse(response)

  • onError(err)

  • onRequestError(err)

  • onResponseError(err)

  • setBaseURL
    is used to set the URL address

    if (process.client) {
          
          
      this.$axios.setBaseURL('http://api.example.com')
    }
    
  • setHeader
    is used to set the request header Header

    this.$axios.setHeader('Authorization', '456')
    
  • setToken
    can easily set the global authentication header with this

     this.$axios.setToken('123', 'Bearer')
    

use

Just use it directly, other things nuxtjs has already done for you

async asyncData({
     
      $axios }) {
    
    
  const ip = await $axios.$get('http://icanhazip.com')
  return {
    
     ip }
}

nuxt3

Will update later

Guess you like

Origin blog.csdn.net/qq_45859670/article/details/129666411