import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://127.0.0.1:80","http://127.0.0.1") .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS") .allowCredentials(true).maxAge(3600); } }
allowedOrigins里面可以直接写*,表示所有地址,可是在前后端分离的时候我们会用到cookies,写*前端请求的时候不会带cookies,所以还是直接写ip地址吧!
springboot 中有一个注解加在你需要跨域的接口上就可以了
@CrossOrigin(origins = "*") @RequestMapping("/queryContentCollectTb") public ContentCollectTbEntity queryContentCollectTb(@RequestParam String articleIdB){ ContentCollectTbEntity contentCollectTb = articleCollectTbService.queryContentCollectTb(articleIdB); return contentCollectTb; }