Fork me on GitHub

同源策略SpringBoot允许跨域请求配置

SpringBoot跨域设置

完全允许(测试环境)

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;

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")            // 通配符来源
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        // 必须显式关闭凭证
                        .allowCredentials(false);      // 与allowedOrigins("*")兼容
            }
        };
    }
}

允许特定域名 + 携带凭证(推荐)

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;

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("https://www.abc.com:[*]","http://IP:[*]","http://localhost:[*]") // 域名白名单
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .allowCredentials(true)         // 允许cookie
                        .maxAge(3600);                  // 预检请求缓存
            }
        };
    }
}

测试

浏览器打开指定的系统-》F12,控制台执行如下代码

var token= "your token";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://IP:Port/gateway/code');
xhr.setRequestHeader("x-access-token",token);
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}
posted @ 2025-03-21 15:20  秋夜雨巷  阅读(145)  评论(0)    收藏  举报