美文网首页
Nuxt.js 解决跨域

Nuxt.js 解决跨域

作者: LELIN | 来源:发表于2021-07-15 17:32 被阅读0次

根据nuxt官方文档提供的axios module

安装:
npm install @nuxtjs/axios @nuxtjs/proxy --save

nuxt.config.js 配置

  modules: [
    '@nuxtjs/axios','@nuxtjs/proxy'
  ],
  axios: {
      proxy: true, // 表示开启代理
      prefix: '/api', // 表示给请求url加个前缀 /api
      credentials: true // 表示跨域请求时是否需要使用凭证
  },
  proxy: {
    '/api': {
      target: 'http://127.0.0.1:8080', // 目标接口域名
      changeOrigin: true, // 表示是否跨域
      pathRewrite: {
        '^/api': '/', // 把 /api 替换成 /
      }
    }
  },
  build: {
    vendor: ['axios'] //为防止重复打包
  }

主要增加四点内容:
1、modules
2、axios配置
3、proxy配置
4、build 打包配置

index.vue 中使用

asyncData(content) {
    axios.get('/api').then (res => {
        console.log(res)
    }).catch(err=> console.log(err))
},

相关文章

网友评论

      本文标题:Nuxt.js 解决跨域

      本文链接:https://www.haomeiwen.com/subject/lslmpltx.html