当前位置:   article > 正文

Vue3+vite搭建项目全局引入axios,并且接解决axios跨域问题_vite 引入axios

vite 引入axios

全局引入axios
在main.js里面引入

import { createApp } from 'vue'
import App from './App.vue'
// import router from './router'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$http = axios
app.mount('#app')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在你的xxxx.vue里面使用:

<script>
import { getCurrentInstance } from "vue";
export default {
  setup() {
    const { proxy } = getCurrentInstance();
    proxy.$http
      .get("/api/你的数据接口")
      .then((response) => {
        console.log(response);
      });
  },
};
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

解决跨域
在根目录vite.config.js里面:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    host: '0.0.0.0',
    port: 3000,
    proxy: {
      '/api': {
        target: '你接口的域名',	//实际请求地址
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
    }
  }
})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/227615
推荐阅读
相关标签
  

闽ICP备14008679号