AngularJS 从 Play Framework 后端渲染 Raw JSON

AngularJS Render Raw JSON from Play Framework backend

我有一个简单的 AngularJS 应用程序,它应该调用 URL 并按原样呈现结果 JSON。这是 index.html:

<!doctype html>
<html ng-app>
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
        <script>
        function Hello($scope, $http) {
            $http.get('http://localhost:9000/status').
            success(function(data) {
                $scope.greeting = data;
            });
        }
    </script>
    </head>

    <body>
        <div ng-controller="Hello">

            <pre>{{greeting | json}}</pre>
        </div>
    </body>
</html>

url 当我从浏览器调用时,我得到了我期望的 JSON,但是当我调用 localhost:8080[=16= 时我看到了一个空白页面]

然后我尝试从完全不同的服务器调用不同的 URL:

http://rest-service.guides.spring.io/greeting

这会按预期呈现内容:

{"id":1,"content":"Hello, World!"}

我是 运行 NGINX 服务器中的 index.html,而我的后端服务器 运行 在端口 9000 上由 Play 框架提供服务。这是我的 NGINX 配置:

server {
    listen       8080;
    server_name  localhost;
    root /Users/joesan/Projects/Sandbox/my-app;

    #charset koi8-r;

    access_log  logs/host.access.log  main;

    location / {
            # If you want to enable html5Mode(true) in your angularjs app for pretty URL
            # then all request for your angularJS app will be through index.html
            try_files $uri /index.html;
    }

    # /api will server your proxied API that is running on same machine different port
    # or another machine. So you can protect your API endpoint not get hit by public directly
    location /api {
            proxy_pass http://localhost:9000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

我明白问题出在哪里了。我必须在我的 Play 应用程序上启用 CORS 过滤器。我正在使用 Play 框架 2.5,这里是 Play 中关于如何配置 CORS 过滤器的参考文档:

https://www.playframework.com/documentation/2.5.x/CorsFilter

此外,在 application.conf 中,我必须执行以下操作:

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

    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null

    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST"]
  }