Java SpringBoot解决前后端分离项目的跨域问题

一、前言

现在越来越多的项目都是前后端分离的模式,这个时候就会出现一个跨域的问题。这边博客主要记录一下java中SpringBoot是如果解决跨越的问题。

二、报错截图

报错代码:onlineFund:1 Access to XMLHttpRequest at ‘http://localhost:8088/user-userdetail/any/get’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

在这里插入图片描述

三、解决思路

使用配置的方式,后台配置支持跨越即可。新建一个配置类,配置allowedOrigins为*。

四、配置代码

新建WebmvcConfig配置类继承WebMvcConfigurer,可以把下面的代码复制过去直接使用。

package top.zywork.configuration;

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

/**
 * WebMvc配置,增加跨域配置<br/>
 *
 * 创建于2020-04-27<br/>
 *
 * @author 危锦辉
 * @version 1.0
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "OPTIONS")
                .maxAge(3600);
    }
}

猜你喜欢

转载自blog.csdn.net/Wjhsmart/article/details/105784778