声明一个名为axiostest.js 的文件

//引入axios
import axios from 'axios';

//创建一个axios
export let axios1 = axios.create({
//设置baseURL是为了之后做代理
  baseURL: '/api1',
  timeout: 5000
});

//创建第二个axios
export let axios2 = axios.create({
  baseURL: '/api2',
  timeout: 5000
});

 配置vue.config.js

module.exports = {
  publicPath: './',
  productionSourceMap: true,
  devServer:{
    // 这里填IP地址
    host: "192.168.666.666",,
    port: 8080,
    open: true, //浏览器自动打开页面
    proxy: {
        //第一个代理,这里的/api1和/api2就对应了第一步的 baseURL
      "/api2": {
        target: "https://www.666.com",//只要是以/api2开头的链接都会被代理到 这个target属性所代表的位置(我这里是:https://www.666.com)
        ws: false,
        changeOrigin: true,
        cookieDomainRewrite: {
          "*": ""
        },
        cookiePathRewrite: {
          "*": ""
        },
        pathRewrite: {
          "^/api2": ""  //这里是将/api2替换为空字符串“” ,也就是删除的意思
        }
      },
        //第二个代理
      "/api1/": {
        target: "http://www.888.com",
        ws: false,
        changeOrigin: true,
        cookieDomainRewrite: {
          "*": ""
        },
        cookiePathRewrite: {
          "*": ""
        },
        pathRewrite: {
          "^/api1": ""
        }
      }
    }
  }
}

配置成功后使用

<script>
//毫无疑问,先引入
import { axios1, axios2 } from '@/libs/axiostest.js'
export default {
  name:'AxiosTest1',
  mounted(){
    this.getMooc();
    this.hotwords();
  },
  methods:{
    getMooc(){
      axios1.get('/products',{
        params:{
          categoryId: 100012
        }
      }).then((data)=>console.log('data',data))
    },
    hotwords(){
      axios2.post('/search/hotwords').then((data)=>console.log('hotwords',data))
    }
  }
}
</script>

访问成功,happy的很,如果有用一键三连 

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐