vue3使用两个后端接口

80 阅读1分钟

1.安装并引入axios

import axios from 'axios'

// 全局配置 axios
const Api = axios.create({
    baseURL: '/api', // 域名配置,可添加变量配置文件定义
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    },
    withCredentials: true, // 跨域请求时是否需要使用凭证
    timeout: 10*60*1000, // 请求超时时间ms
});
const Api_java = axios.create({
    baseURL: '/java', // 域名配置,可添加变量配置文件定义
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    },
    withCredentials: true, // 跨域请求时是否需要使用凭证
    timeout: 10*60*1000, // 请求超时时间ms
});

const app = createApp(App)
app.use(router)
app.use(TDesign)
app.config.globalProperties.$axios=Api
app.config.globalProperties.$axios_java=Api_java
app.config.globalProperties.$echarts= echarts;
app.mount('#app')

2.配置代理

server: {
  proxy: {
    '/api': {
      target: 'http://127.0.0.1:5000', //接口域名
      changeOrigin: true,             //是否跨域
      ws: true,                       //是否代理 websockets
      secure: true,                   //是否https接口
      rewrite: (path) => path.replace(/^/api/,'')
    },
    '/java': {
      target: 'http://127.0.0.1:8088', //接口域名
      changeOrigin: true,             //是否跨域
      ws: true,                       //是否代理 websockets
      secure: true,                   //是否https接口
      rewrite: (path) => path.replace(/^/java/,'')
    }
  }
},

3.使用

图片.png

import {ref,onMounted,onBeforeUnmount,getCurrentInstance} from 'vue'

const { appContext } = getCurrentInstance();

appContext.config.globalProperties.$axios_java.get('/xxx').then((res)=>{
  if(res.status == 200){
    console.log(res.data)
  }
}).catch((error)=>{
  console.log(error)
})


Axios 是一个基于 promise 的 HTTP 库,简单的讲就是可以发送get、post请求。说到get、post,大家应该第一时间想到的就是Jquery吧,毕竟前几年Jquery比较火的时候,大家都在用他。但是由于Vue、React等框架的出现,Jquery也不是那么吃香了。也正是Vue、React等框架的出现,促使了Axios轻量级库的出现,因为Vue等,不需要操作Dom,所以不需要引入Jquery.js了。