如何在flex环境和PHP运行时中使用GAE处理CORS(或任何标题)?
问题描述:
I'm using Google AppEngine with PHP7.2 Runtime and i'm facing a problem with CORS.
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
With GAE flexible environment, it seems that is not possible:
- No handlers.http_headers variable is usable
- Sets Headers directly in the PHP code does not work:
.
$response->headers->add(
[
'Access-Control-Allow-Origin' => 'http:/blabla-dot-my-app.appspot.com',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
]
);
It seems that GAE LB is dropping every header we want to set.
So... how to handle CORS (or other headers) with GAE in flexible environment and PHP7.2 runtime ?
答
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:
- Using the code directly:
...
$response->headers->add(
[
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST',
'Access-Control-Allow-Headers' => 'Content-Type,Authorization',
]
);
- overriding the nginx configuration used by PHP runtime (cf 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;
}