springboot配置允许跨域

在前后端分离的架构中,允许跨域请求是一个很重要的设置。SpringBoot项目中允许跨域请求比较简单,只需要我们定义好配置类即可。

com.example.emos.api.config包里面创建CorsConfig类,然后设置允许跨域请求。

 

package com.example.emos.api.config;

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 implements WebMvcConfigurer {

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

}

  

posted @ 2023-10-31 23:51  sgj191024  阅读(447)  评论(0编辑  收藏  举报