SpringBoot配置API跨域

SpringBoot配置API跨域

新建CorsConfig配置类,
在WebMvcConfigurer里配置
addCorsMappings跨域资源映射

package cn.ath.knowwikibackend.cors;

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 CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        //允许所有域名
                        .allowCredentials(true)
                        //对所有请求路径
                        .allowedOriginPatterns("*")
                        //允许cookie等凭证
                        .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
                        //允许请求头Header
                        .allowedHeaders("*")
                        //允许响应头Header
                        .exposedHeaders("*")
                        //默认30分钟
                        .maxAge(24*60*60);
            }
        };
    }
}

你可能感兴趣的:(SpringBoot技术笔记,JavaWeb笔记,spring,boot,后端,java)