为Lagom Java启用CORS过滤器 [英] Enabling the CORS filter for Lagom Java

查看:147
本文介绍了为Lagom Java启用CORS过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照跨域资源共享的说明进行操作,从localhost:3000(我的有角度的前端正在运行)访问localhost:9000(运行我的微服务的Lagom GateWay).但我仍然面对:

I have followed the instruction of Cross-Origin Resource Sharing in order to access localhost:9000 (Lagom GateWay where my microservices are running) from localhost:3000 (where my angular front-end is running). but still I face:

XMLHttpRequest cannot load http://localhost:9000/api/myservice. No 'Access-Control-Allow-Origin' header is present on the requested resource 

有人有启用CORS的示例或项目吗?

doe anyone have a sample or project that enabling CORS works there?

推荐答案

为了其他人使用Angular 4前端和lagom后端项目.我设法解决了这种方式.

For the sake of others working with Angular 4 front-end and lagom backend project. I have managed to solve this way.

*我在api和impl中的build.sbt中添加了以下这一行*

*I added this line below in my build.sbt in both api and impl *

libraryDependencies + =过滤器

libraryDependencies += filters

在我的impl目录中,我创建了文件夹过滤器,并在下面添加了代码

import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.HttpFilters;

import javax.inject.Inject;

public class Filters implements HttpFilters {

    @Inject
    CORSFilter corsFilter;

    public EssentialFilter[] filters() {
        return new EssentialFilter[]{corsFilter.asJava()};
    }
}

在我的application.conf中,我添加了以下代码

play.filters.hosts {
  # Allow requests to example.com, its subdomains, and localhost:9000.
  allowed = ["localhost:5000", "localhost:9000"]
}

play.http.filters = "filters.Filters"

play.filters.cors {
  # Filter paths by a whitelist of path prefixes
  pathPrefixes = ["/"]

  # The allowed origins. If null, all origins are allowed.
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}

此后,我重新启动了lagom微服务,它的运行就像一个魅力.

After this, i restarted my lagom microservices and it worked like a charm.

这篇关于为Lagom Java启用CORS过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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