如何在Flex环境和PHP运行时中使用GAE处理CORS(或任何标头)? [英] How to handle CORS (or whatever headers) with GAE in flex environment and PHP runtime?

查看:43
本文介绍了如何在Flex环境和PHP运行时中使用GAE处理CORS(或任何标头)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Google AppEngine与PHP7.2运行时一起使用,并且遇到了CORS问题.

I'm using Google AppEngine with PHP7.2 Runtime and i'm facing a problem with CORS.

在GAE 标准环境中,可以使用app.yaml(handlers.http_headers)cf(

With GAE standard environment, it is possible to set headers with app.yaml (handlers.http_headers) cf(https://cloud.google.com/appengine/docs/standard/php/config/appref#handlers_element):

handlers:
- url: /images
  static_dir: static/images
  http_headers:
    X-Foo-Header: foo
    X-Bar-Header: bar value

在GAE 灵活环境中,这似乎是不可能的:

With GAE flexible environment, it seems that is not possible:

  • 没有处理程序.http_headers变量可用
  • 直接在PHP代码中设置标头不起作用:

.

$response->headers->add(
    [
        'Access-Control-Allow-Origin' => 'http:/blabla-dot-my-app.appspot.com',
        'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
    ]
);

GAE LB似乎正在丢弃我们要设置的每个标头.

It seems that GAE LB is dropping every header we want to set.

那么...如何在灵活的环境和PHP7.2运行时中使用GAE处理CORS(或其他标头)?

So... how to handle CORS (or other headers) with GAE in flexible environment and PHP7.2 runtime ?

推荐答案

最后,我是唯一在此问题"上存在问题的人.在 dispatch.yaml 中定义的路由设置是因为我没有请求正确的GAE 服务.

Finally, I was the only one faulty on this "issue". The routing defined in dispatch.yaml was set in a way that I was not requesting the right GAE service.

尽管如此,我了解到可以通过两种方式设置标头:

Nevertheless, I've learned that it possible to set headers in two manners:

  • 直接使用代码:

...

$response->headers->add(
    [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Methods' => 'GET, POST',
        'Access-Control-Allow-Headers' => 'Content-Type,Authorization',
    ]
);

  • 覆盖PHP运行时使用的nginx配置(请参见 https://cloud.google.com/appengine/docs/flexible/php/runtime#customizing_nginx ):
  • ...

    # CORS
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET,POST';
    add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization';
    
    location / {
      # CORS (again)
      if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
      }
      # try to serve files directly, fallback to the front controller
      try_files $uri /$front_controller_file$is_args$args;
    }
    

    这篇关于如何在Flex环境和PHP运行时中使用GAE处理CORS(或任何标头)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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