Angular通過http發送post請求至SpringBoot的Controller,由於同源策略的保護,遇到跨域問題:
• 源(origin)就是協議(http)、域名(localhost)和端口號(8080),若地址里面的協議、域名和端口號均相同則屬於同源
解決方法:SpringBoot增加跨域請求支持
一:全局配置(推薦)
package com.example.example1.Default; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Created by BLIT on 2019/3/7. */ @Configuration @EnableWebMvc public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { //設置允許跨域的路徑 registry.addMapping("/**") //設置允許跨域請求的域名 .allowedOrigins("*") //也可以指定域名 .allowedOrigins("http://192.168.0.0:8080","http://192.168.0.1:8081") //是否允許證書 不再默認開啟 .allowCredentials(true) //設置允許的方法 .allowedMethods("*") //跨域允許時間 .maxAge(3600); } }
二:局部配置
添加注解:@CrossOrigin(origins = {"http://localhost:4200","null"})
可以注解在單個方法上,也可以注解在整個controller上