Vuejs中设置代理进行跨域的方法

在vue工程中根目录增加一个配置文件:vue.config.js

module.exports = {
    // 修改的配置
    devServer: {
        host:"0.0.0.0",
        disableHostCheck: true,
        //  https: true,
        proxy: {
            "/api/": {
                "target": "http://localhost:8090/",
                changeOrigin: true,
                ws: true,
                
                pathRewrite: {
                    '^/api': '/'
                }
            },"/rest/": {
                "target": "http://localhost:8000/",
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/rest': '/'
                }
            }
        }
    }
}

安装axios

cnpm install axios --save-dev

在main.js中引入axios

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
Vue.use(axios);
Vue.config.productionTip = false
Vue.prototype.$axios = axios;
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

在业务代码中增加一个方法和一个按钮

  methods: {
    getData() {
      window.console.info(1111111);
      // 1:可以访问后端接口已经做了跨域设置的接口this.$axios.get("http://localhost:8090/hello").then((data)=>window.console.info(data))
      //2:可以直接调用使用Vue做了代理的接口
      // this.$axios.get("/api/hello").then((data)=>window.console.info(data))
      // this.$axios.get("/rest/user/").then((data)=>window.console.info(data))
      this.$axios
        .get("http://localhost:8090/hello")
        .then(data => window.console.info(data));
    }
  }

按钮触发事件

 <button @click="getData()">请求接口</button>

获取如下内容并打印出来。
在这里插入图片描述
如果不想使用代理,则可以在后端接口做跨域支持:
springboot中在主类加入如下两个方法:

private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
		corsConfiguration.addAllowedHeader("*"); // 2允许任何头
		corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 4
		return new CorsFilter(source);
	}

后端跨域之后,前端也不用再设置代理访问了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值