SpringBoot解決跨域請求問題 - 配置Cors

報錯: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
報錯
就是說跨域問題。

HTTP訪問控制(CORS)

1.使用@CrossOrigin註解

如果想要對某一接口配置 CORS,可以在方法上添加 @CrossOrigin 註解 :

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
}

如果想對一系列接口添加 CORS 配置,可以在類上添加註解,對該類聲明所有接口都有效:

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}

2.添加配置類

如果想添加全局配置,則需要添加一個配置類 :
目錄結構

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

學習自 SpringBoot配置Cors解決跨域請求問題.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章