spring boot 结合 vue 出现的跨域问题

当我们使用spting boot 前端界面是vue的时候会发现vue请求不到后端界面这个时候就需要我们做一下跨域问题的处理

1.首先你要解决跨域问题肯定是要给后端接口发请求的对吧所以你要先引入axios对不对讲道理

一.npm install axios --save

二.在main.js中引入axios,挂载到Vue原型中

import axios from 'axios'

Vue.prototype.$axios=axios

2.解决跨域问题

   一.vue前端解决问题

confg/index.js中,加入代理列表

之前的proxyTable是空的所以你加上这个代理列表

 "/backserver": {// 这个就是你发请求的地址

        target: "http://localhost:9999",//这个就是你自己项目的地址

        pathRewrite: {

          '^/backserver': ''//这个和上面请求的地址一致

        },

        changeOrigin: true

      }

注意:解决完毕后需要重启客户端

请求的时候就可以这么写了

二.服务端解决问题

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

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

没有亲自测试

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值