nuxt中axios的配置

版权声明:前端菜鸟--人间草木所有 https://blog.csdn.net/qq_43258252/article/details/88644165

需要npm axios?

刚开始,我以为需要像普通的vue SPA开发那样,需要npm axios,这种方式的确可以生效。但在使用时并不方便。尤其是设置代理比较麻烦,而且在asyncData里与在普通methods里使用方式不一样。
后来在nuxt的github上发现了nuxt是默认集成了axios的,所以不需要npm axios,但是需要进行适当的配置。

以上是百度到的,发现老是报错,现在网上的教程完全是在扯淡,npm axios 是不需要安装了,但是 @nuxtjs/axios 要安装啊

第一步:

npm 安装@nuxtjs/axios,文件根目录下安装,指令如下

npm install @nuxtjs/axios

第二步:

在  nuxt.config.js 文件中 配置 axios 和 proxy 代理  如下图:

方便你复制~~~~ 

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, // 表示开启代理
    prefix: '/api', // 表示给请求url加个前缀 /api
    credentials: true // 表示跨域请求时是否需要使用凭证
  },

  proxy: {
    '/api': { 
      target: 'https://www.apiopen.top', // 目标接口域名
      pathRewrite: {
        '^/api': '/', // 把 /api 替换成 /
        changeOrigin: true // 表示是否跨域
      }    
    }
  },

  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
    },
    vendor: ['axios'] // 为防止重复打包
  }
}

 

第三步:

在组件中使用

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

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

猜你喜欢

转载自blog.csdn.net/qq_43258252/article/details/88644165
今日推荐