Spring MVC CORS 跨域资源共享

说明

名称 文档 说明
网关 CORS 跨域资源共享 Spring Cloud Gateway 网关 CORS 跨域资源共享
Security CORS 跨域资源共享 Spring Security CORS 跨域资源共享
MVC CORS 跨域资源共享 本文
基于注解配置 CORS 注解 CrossOrigin 跨域资源共享

配置

package cn.com.xuxiaowei.demo2.config;

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

/**
 * Ajax 跨域
 * <p>
 * {@link WebMvcConfigurationSupport} 优先级比 {@link WebMvcConfigurer} 高
 * <p>
 * 使用了 {@link WebMvcConfigurationSupport} 之后,{@link WebMvcConfigurer} 会失效
 *
 * @author xuxiaowei
 */
@Configuration
public class WebMvcConfigurerConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        // Ajax 请求指定域,需要提供协议、端口
        String[] origins = {"http://127.0.0.1:10001"};

        registry.addMapping("/**")
                // 域
                .allowedOrigins(origins)
                // 默认为 GET, HEAD, POST
                // 可以为 GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
                .allowedMethods("GET", "HEAD", "POST")
                // 默认为 1800秒(30分钟)
                .maxAge(1800)
                // 浏览器是否应将凭据(如Cookie和跨域请求)发送到带注释的端点。
                .allowCredentials(true);

    }

}