vue跨域解决方案之--proxy代理

9 篇文章 0 订阅
8 篇文章 0 订阅

声明一个名为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的很,如果有用一键三连 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值