vue axios在开发中遇到的问题

第一次学vue,自己摸索了好久。用axios的时候遇到了几个问题。跨域,还有就是多个proxyTable配置的时候出现的问题。记下,方便以后查阅

var _this=this;
 _this.$axios.get("http://xxxx/js/shopData.json").then(res=>{
       console.log(res.data)
})

这样写乍一看是没有问题的,但是浏览器抛出了一个错误

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

什么意思呢?就是跨域了,那么应该怎么来解决这个跨域的问题?

1.首先在main.js配置如下代码
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api'
Axios.defaults.headers.post['Content-Type'] = 'application/json';
2.其次在index.js 中的proxyTable配置如下代码
 proxyTable: {
      '/api':{
        target: "http://xxxx/",
        secure: false,
        changeOrigin:true,
        pathRewrite:{
            '^/api':''
        }
      }
    },

然后把axios改成

var _this=this;
 _this.$axios.get("/js/shopData.json").then(res=>{
       console.log(res.data)
})

假设接口服务器在 https://xxxx,本地服务器是 http://localhost:8080

原接口 https://xxxx/js/shopData.json 代理到 http://localhost:8080/api/js/shopData.json
撒花,跨域成功~~~

如果我们有多个接口呢?webpack devserver proxy 如何匹配代理多个路径到不同host?

1.首先在index.js 中的proxyTable配置

    proxyTable: {
      '/api':{
        target: "http://xxxx/",
        secure: false,
        changeOrigin:true,
        pathRewrite:{
            '^/api':''
        }
      },  
      '/test':{
        target: "https://yyy/",
        secure: false,
        changeOrigin:true,
        pathRewrite:{
            '^/test':''
        },
      }  
    },

2.然后请求第二个接口就可以了,第二个接口为 https://yyy/order.php

var _this=this;
 _this.$axios.get("/test/order.php").then(res=>{
       console.log(res.data)
})

问题来了,报错
http://localhost:8080/api/test/order.php 403 (Forbidden)
找不到这个东西,为啥有带了api,难道自动匹配到第一个接口,在第一个接口找不到php这个文件才报错??
细想了一下会不会axios的配置默认带了api回头一看

3.更改axios的配置

Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/'
Axios.defaults.headers.post['Content-Type'] = 'application/json';

然后第一个接口url自己带上api就可以访问了/api/js/shopData.json

这个是我在开发中遇到的问题,希望能够帮助到你

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值