springboot 解決跨域 Access to XMLHttpRequest at

小一隻發表於2020-10-27

訪問報錯,跨域問題

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

springboot 配置跨域:

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

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")

                .allowedOrigins("*")

                .allowCredentials(true)

                .allowedMethods("GET", "POST", "DELETE", "PUT")

                .maxAge(3600);

    }
}

一定要加@Configuration註解,之後重啟就可以了

相關文章