App Engine 端点启用 CORS

App Engine Endpoint enable CORS

我在标准环境 v2 端点中有一些方法 class。当从 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: * 响应 header。有什么方法可以启用吗?

答案中描述的问题是我的错(真是意外)。 对于其他在 GAE 上配置 CORS 有问题的人: 如果 CORS 是开箱即用的。但要获得正确的响应,您还必须有正确的请求:

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

方法必须是以下之一:"HEAD", "DELETE", "GET", "PATCH", "POST", "PUT" Origin 几乎可以是任何字符串——您将在响应中取回它。 "null"是一个特殊的关键字,翻译成“*”。 这是负责 header 生成的代码(来自 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 文件导致构建不稳定。