[英]Spring Boot microservice response issue with Angular 2 http call
我正在尝试从我的 Angular 2 前端应用程序向 Spring Boot REST 微服务调用 GET 请求,但是当我调用时,我收到如下错误:
请求的资源上不存在 Access-Control-Allow-Origin 标头
这是我的控制器操作:
@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{
ObjectMapper mapper = new ObjectMapper();
List<Users> useObj = (List<Users>) userRepo.findAll();
return(mapper.writeValueAsString(useObj));
}
当我运行 Angular 时,出现上述错误。 我添加了它的截图
这是来自 Angular 问题还是来自 Spring Boot 微服务响应问题?
由于它们运行在不同的端口上,因此您必须在服务器端允许跨域资源共享 (CORS)。 在 Spring Boot 中,您可以通过将 @CrossOrigin 注释添加到处理程序方法来实现:
@CrossOrigin(origins = "http://localhost:4200")
也可以在控制器类级别添加此注释,以便在该类的所有处理程序方法上启用 CORS。
接受的答案很好,因为它提供了一个有效的解决方案,但它也迫使您在每个控制器的服务器端硬编码客户端的 URL。 您可以改为设置全局 CORS 配置。 如果您的 Web 配置扩展了WebMvcConfigurereAdapter
类,您可以简单地覆盖addCorsMappings
方法。 以下示例为整个应用程序启用 CORS:
@Configuration
public class WebConfig extends WebMvcConfigurereAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
在此处阅读有关 Spring 中 CORS 支持的更多信息
在你的 Application.java 添加一个 bean
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
return bean;
}
它是全局的,适用于您项目的每个控制器。
创建一个实现 javax.servlet.Filter 接口的 Spring Boot 组件类并添加所需的标头解决了我的类似问题。
@Component
public class YourAppCorsFilter implements Filter{
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
}
如果您在将其添加到您的微服务后仍然遇到问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.