在 Spring Data Rest 中启用跨源请求 [英] Enabling cross origin requests in Spring Data Rest

查看:31
本文介绍了在 Spring Data Rest 中启用跨源请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Angular 2 和 Spring Boot 开发的 Web 应用程序.我使用 spring-boot-data-rest 依赖项将我的存储库公开为 HTTP 端点.

I have a web application that I am developing using Angular 2 and Spring Boot. I use the spring-boot-data-rest dependency to expose my repositories as HTTP endpoints.

在开发过程中,我在运行在 8080 端口的本地 tomcat 上运行我的后端 spring boot 项目.为了开发前端,我使用 angular-cli 在端口 4200 上为我的 Angular 2 应用程序提供服务.我在 4200 上运行的前端需要能够访问 8080 上公开的端点,但这不起作用,因为:

During development, I run my backend spring boot project on a local tomcat that runs on port 8080. To develop the frontend, I use the angular-cli to serve my Angular 2 application on port 4200. My frontend running on 4200 needs to be able to hit the endpoints exposed on 8080, but that doesn't work because:

请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源 'http://localhost:4200'.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

如果这些是我在 @RestController 中手动输入的自定义端点,我可以简单地添加 @CrossOrigin 注释:

If these were custom endpoints that I manually typed in a @RestController, I could simply add the @CrossOrigin annotation as such:

@RestController
public class MyController {
    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/whatever")
    public void whatever() {
        //whatever
    }
}

但我显然无法为 spring-boot-data-rest 公开的端点执行此操作.那么,如何使这些端点可以从 http://localhost:4200 源访问?

But I obviously cannot do this for my endpoints exposed by spring-boot-data-rest. So, how can I make those endpoints accessible from the http://localhost:4200 origin?

推荐答案

我已经使用我的自定义 CORS 过滤器使其工作:

I've used my custom CORS filter to make it work:

/**
 * Filter for enabling CORS support.
 */
@Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
                                    final FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addIntHeader("Access-Control-Max-Age", 10);
        filterChain.doFilter(request, response);
    }
}

这篇关于在 Spring Data Rest 中启用跨源请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆