springboot+vue跨域问题

vue main.js

axios.defaults.withCredentials = true

在这里插入图片描述
springboot 新建CorsConfig.java文件
在这里插入图片描述

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;

/**
 * 设置允许跨域
 * @author bekey
 */
@Configuration
public class CorsConfig {
    
    
    /**
     允许任何域名使用
     允许任何头
     允许任何方法(post、get等)
     */
    private CorsConfiguration buildConfig() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // // addAllowedOrigin 不能设置为* 因为与 allowCredential 冲突,需要设置为具体前端开发地址
        corsConfiguration.addAllowedOrigin("http://localhost:8080");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        // allowCredential 需设置为true
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

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

这样设置以后就能跨域访问了,但是会出现后台session为null的情况。
所以还要加多一步:
在vue根目录 vue.config.js中添加如下代码

module.exports = {
    
    
    devServer: {
    
      //配置跨域
        proxy: {
    
    
            '/api': {
    
    
                target: 'http://localhost:8088/',  //+后台的地址
                changOrigin: true,  //允许跨域
                pathRewrite: {
    
    
                  /* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时
                    实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api
                   */
                  '^/api': '' 
                }
              },
        }
    }
};

axios全局配置中

import axios from 'axios'
export function request(config) {
    
    
    const install = axios.create({
    
    
        baseURL: '/api',				//指定转发地址
        timeOut: 5000
    })
    install.interceptors.request.use(data => {
    
    
        let token = localStorage.getItem("token");
        if (token) {
    
      // 判断是否存在token,如果存在的话,则每个http header都加上token
            data.headers.token = `${
      
      token}`;
        }
        return data
    }, err => {
    
    
        return err
    })
    install.interceptors.response.use(data => {
    
    
        return data
    }, err => {
    
    
        return err
    })
    return install(config)
}

然后就能愉快的继续玩耍啦。

猜你喜欢

转载自blog.csdn.net/weixin_43276017/article/details/112536055