springboot解決跨域

對於前後端分離的項目來說,如果前端項目與後端項目部署在兩個不同的域名下,那麼勢必會引起跨域問題的出現。

基於WebMvcConfigurerAdapter配置加入Cors的跨域

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("/**") 
	                .allowedOrigins("*") 
	                .allowCredentials(true) 
	                .allowedMethods("GET", "POST", "DELETE", "PUT") 
	                .maxAge(3600); 
	    }
}

如果你想做到更細緻也可以使用@CrossOrigin這個註解在controller類中使用。

這樣就可以指定該controller中所有方法都能處理來自http://192.168.41.40:8411中的請求。

@CrossOrigin(origins = "http://192.168.41.40:8411", maxAge = 3600)
@RestController
@RequestMapping("/user")
public class TestController {

 

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