App Engine端点启用CORS

时间:2017-07-12 13:55:49

标签: java cors google-cloud-endpoints

我在Standard Environment v2端点类中有一些方法。从Web客户端调用它们时,首先调用OPTIONS方法以检查是否启用了CORS。 回应是:

HTTP/1.1 200 OK
X-Cloud-Trace-Context: 2a246f2e7f7ddbbf2afeaa71629da259;o=1
Date: Wed, 12 Jul 2017 13:47:20 GMT
Expires: Wed, 12 Jul 2017 13:47:20 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Content-Length: 0
Server: GSE
Content-Type: text/html; charset=UTF-8
Alt-Svc: quic=":443"; ma=2592000; v="39,38,37,36,35"

这里缺少的是Access-Control-Allow-Origin: *响应标头。有没有办法启用它?

1 个答案:

答案 0 :(得分:0)

答案中描述的问题是我的错(多么令人惊讶)。 对于其他在GAE上配置CORS有问题: 如果CORS设置为开箱即用。但要获得正确的答案,您还必须得到正确的要求:

Origin: null
Access-Control-Request-Method: GET

方法必须是以下之一:"HEAD", "DELETE", "GET", "PATCH", "POST", "PUT" Origin几乎可以是任何字符串 - 你会在响应中得到它。 “null”是一个特殊的关键字,被翻译为“*”。 这是负责标题生成的代码(来自GAE源代码):

  public static void allowOrigin(HttpServletRequest request, HttpServletResponse response) {
    String origin = request.getHeader(Headers.ORIGIN);
    // The Origin spec (http://tools.ietf.org/html/draft-abarth-origin-09) allows for the Origin
    // http header value to be "null". This is for cases where a request doesn't have a valid
    // origin; for example, issuing a CORS request from a local file:// rather than a website. In
    // these cases, we'd like to enable CORS to facilitate testing; the mechanism for doing so is
    // to set the Access-Control-Allow-Origin header to '*'.
    origin = NULL_ORIGIN.equals(origin) ? "*" : origin;
    response.setHeader(Headers.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
  }

由于错误合并的Gradle文件,我的第二个问题是构建不稳定。