SpringBoot工程解决跨域问题

本文介绍了在SpringBoot项目中如何配置解决跨域问题,适用于前后端联调时遇到的接口跨域访问限制。通过添加配置类设置允许的来源和允许携带cookie,并在Vue项目的axios中设置withCredentials为true,确保跨域请求能携带cookie。
摘要由CSDN通过智能技术生成

SpringBoot + vue axios 前后端工程解决跨域问题

使用场景: 常用于前后端联调过程中,出现接口访问跨域问题,至于跨域的原理,这里不做细说,自行百度,解决方法如下

1.添加配置类

package com.xy.quickapp.enterprise.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by kang.zou
 * on 2020/2/21
 */
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

    /**
     * 设置前后端跨域
     * @return
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer2(){
        return new WebMvcConfigurer() {
            /**
             * 设置头 使可以跨域访问
             * @param registry
             * @since 4.2
             */
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .maxAge(3600)
                        .allowCredentials(true);
            }
        };
    }
}

allowOrigins (允许哪些资源访问)可以从配置中读取,这样方便维护
allowCredentials(允许cookie、session跨域)

2.前端vue项目中axios中设置

2.1 main.js中设置
Vue.prototype.$axios = axios
axios.defaults.withCredentials =true;

2.2 axios单独设置
withcredentials:true

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值