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; }

本文介绍如何在 SpringBoot 应用中配置跨域访问,包括通过 WebConfig 类全局设置 CORS 支持,并允许特定来源的请求携带 Cookies。此外还展示了如何在控制器方法级别使用 @CrossOrigin 注解实现跨域。
970

被折叠的 条评论
为什么被折叠?



