vue-cli3配置axios代理跨域(二)——配置步骤

关于代理跨域的原理,请查看:https://blog.csdn.net/qq_36485978/article/details/100016790

一、安装vue

vue-cli3安装插件用add命令。

 vue add axios

安装完之后会在src目录下自动生成一个plugins文件夹,在main.js中会自动引入axios,所以不需要再添加什么了。

二、配置代理跨域

在项目根目录下建立vue.confige.js文件,添加如下配置proxy:

module.exports = {
  // 选项...
  publicPath: './', //发布路径,用相对路径,不然会报错
  lintOnSave: false, //是否开启eslint校验
  devServer: {
    proxy: { //配置代理,解决跨域请求后台数据的问题
      '/api': {
        target: 'http://127.0.0.1:8081', //后台接口
        ws: true, //是否跨域
        changeOrigin: true,
        pathRewrite: {
          '^/api':'/'
        }
      }
    }
  }
}

三、在文件中测试现在是否可以跨域请求

下面是.vue文件中向8081端口的/test接口请求数据的示例

<template>
  <div class="hello">
    <button class="testButton" @click="testGet()">测试连接</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods: {
    testGet: function() {
      axios.get('/api/test').then(function(res) {  //api就是http://localhost:8081,在proxy中配置过
        if (res.status == "200") {
          console.log(res);
        } else {
          alert("状态码非200");
        }
      }).catch(function (res) {
        console.log(res);
      })
    }
    
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

可以看到服务器端(8081端口)返回了结果

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值