springboot+vue前后端分离跨域问题

1、同源策略

同源策略是一种约定,它是浏览器最核心也最基本的安全功能,同源是指"协议+域名+端口"三者相同,比如http://localhost:8080与http://localhost:8181就不是同源。
在这里插入图片描述

2、前后端分离跨域

前后端分离的项目前后端服务是使用的不同端口,比如一个vue项目,前端使用的是8080端口,为了不与前端端口重合,这里后端使用了8181端口,那么前端想在8080端口调用后端8181端口是无法实现的,这时候就需要解决跨域问题。

3、通过前端解决

在vue项目的根路径新建一个vue.config.js文件,然后在devServer节点中新建一个proxy节点,在proxy节点中就开始写跨域的配置。

// 跨域配置
module.exports = {
    
    
    devServer: {
    
    
        open:true,
        port: 8091,
        proxy: {
    
        //设置代理,必须填
            '/proxy': {
    
       //设置拦截器  拦截器格式:斜杠+拦截器名
                target: 'http://localhost:8090',   //代理的目标地址
                changeOrigin: true,     //是否设置同源,输入是的
                pathRewrite: {
    
         //路径重写
                    '^/proxy': '' //选择忽略拦截器里面的内容
                }
            }
        }
    }
}

然后在项目的src目录下新建一个utils文件夹,里面新建一个request.js文件,里面的代码如下。

import axios from 'axios'

const request = axios.create({
    
    
    timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
    
    
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    // config.headers['token'] = user.token;  // 设置请求头
    return config
}, error => {
    
    
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
    
    
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
    
    
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
    
    
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
    
    
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)
export default request

在使用前,先在script标签中导入这个js文件,然后发起请求,在发起请求的时候,一定要在你的原来的地址上加上/proxy,因为我们在vue.config.js已经对请求进行了配置,只要请求里面含有/proxy就会被拦截下来,然后通过代理访问代理中设置的地址
在这里插入图片描述

4、通过后端解决

在后端项目中新建一个配置类CorsConfig,代码如下:

@Configuration
public class CorsConfig {
    
    
    //当前跨域请求最大有效时长,这里默认1天
    private static final long MAX_AGE=24*60*60;
    private CorsConfiguration buildConfig(){
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");//设置访问源地址
        corsConfiguration.addAllowedHeader("*");//设置访问源请求头
        corsConfiguration.addAllowedMethod("*");//设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter(){
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buildConfig());//对接口配置跨域设置
        return new CorsFilter(source);
    }
}


猜你喜欢

转载自blog.csdn.net/weixin_44153131/article/details/129272743