springBoot项目解决跨域问题

使用场景:当前后台地址不在一个域上的时候会出现跨域的问题,此时需要服务端解决跨域问题。

解决方法:

1.添加如下类即可解决跨域问题

package com.gocom.buintelligence.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域配置
 */
@Component
public class CorsConfig implements WebMvcConfigurer {

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

2.通过nginx转发将接口地址设置到同一个域下也可以解决跨域问题

修改nginx配置文件:/etc/nginx/conf.d/default.conf

添加以下内容:根据自己的实际情况进行接口转发配置即可(前端就可以通过相同的域访问不同的接口地址)

然后重启nginx: systemctl restart nginx

猜你喜欢

转载自blog.csdn.net/wangpei930228/article/details/114310845
今日推荐