Configuration of axios in nuxt

 

Need npm axios?

At the beginning, I thought that npm axios was needed, just like the common vue SPA development, and this way could work. But it is not convenient to use. In particular, setting up agents is cumbersome, and in asyncData is not the same as in normal methods.
Later on github of nuxt It is found that nuxt integrates axios by default, so npm axios is not required, but proper configuration is required.

The above is from Baidu. I always find that there are errors. Now online tutorials are just bullshit. npm axios doesn't need to be installed, but @ nuxtjs/axios needs to be installed

 

Step one:

npm installs @ nuxtjs/axios in the root directory. The instructions are as follows

npm install @nuxtjs/axios

 

The second step:

Configure axios and proxy proxy in the file nuxt.config.js as follows:

Easy to copy

import pkg from './package'

export default {
  mode: 'universal',

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },

  /*
  ** Global CSS
  */
  css: [
    'iview/dist/styles/iview.css'
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '@/plugins/iview'
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios'
  ],

  axios: {
    proxy: true, // Indicates open agent
    prefix: '/api', // Indicates to prefix the request url / api
    credentials: true // Indicates whether credentials are required for cross domain requests
  },

  proxy: {
    '/api': { 
      target: 'https://www.apiopen.top ', / / target interface domain name
      pathRewrite: {
        '^/api': '/', // Replace / api with/
        changeOrigin: true // Indicates whether cross domain
      }    
    }
  },

  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
    },
    vendor: ['axios'] // To prevent repeated packaging
  }
}

 

The third step:

Use in components

<template>
  <div>my</div>
</template>
<script>
export default {
  created () {
    this.allList()
  },
  methods: {
    allList () {
      this.$axios.post(`/novelSearchApi?name=The Lost Tomb`).then(res => {
        console.log(res)
      })
    }
  }

}
</script>
<style scoped>
</style>

 

Tags: axios npm Vue github

Posted on Mon, 02 Dec 2019 17:08:17 -0500 by gassaz