【发布时间】:2018-02-06 15:09:26
【问题描述】:
我一直在尝试在 Google 应用引擎上启用 CORS 标头,但我在互联网上找到的所有方法都不适合我。
我的应用程序在 Python/Django 上,我希望我的前端应用程序(单独托管)能够在 Google App Engine 上对我的后端平台进行 API 调用。
2017 年 1 月的发行说明说
我们正在更改可扩展服务代理 (ESP) 的行为,以默认拒绝跨域资源共享 (CORS) 请求
可以看到here
而他们给出的启用CORS的解决方案是在服务的OpenAPI配置中添加如下sn-p。
"host": "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog",
"x-google-endpoints": [
{
"name": "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog",
"allowCors": "true"
}
],
...
所以我按照this 的例子在我的代码库中创建了两个文件
openapi.yml:
swagger: "2.0"
info:
description: "Google Cloud Endpoints APIs"
title: "APIs"
version: "1.0.0"
host: "echo-api.endpoints.<PROJECT-ID>.cloud.goog"
x-google-endpoints:
- name: "echo-api.endpoints.<PROJECT-ID>.cloud.goog"
allowCors: "true"
paths:
"/api/v1/sign-up":
post:
description: "Sends an email for verfication"
operationId: "signup"
produces:
- "application/json"
responses:
200:
description: "OK"
parameters:
- description: "Email address of the user"
in: body
name: email
required: true
schema:
type: string
- description: "password1"
in: body
name: password1
required: true
schema:
type: string
- description: "password2"
in: body
name: password2
required: true
schema:
type: string
openapi-appengine.yml:
swagger: "2.0"
info:
description: "Google Cloud Endpoints API fo localinsights backend server"
title: "Localinsights APIs"
version: "1.0.0"
host: "<PROJECT-ID>.appspot.com"
然后我运行了这个命令:
gcloud service-management deploy openapi.yml
然后我编辑了我的 app.yml 文件,使其看起来像这样(添加的是 endpoints_api_service。在添加之前,应用程序正在部署,没有任何错误):
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT myapp.wsgi
beta_settings:
cloud_sql_instances: <cloud instance>
runtime_config:
python_version: 3
automatic_scaling:
min_num_instances: 1
max_num_instances: 1
resources:
cpu: 1
memory_gb: 0.90
disk_size_gb: 10
env_variables:
DJANGO_SETTINGS_MODULE: myapp.settings.staging
DATABASE_URL: <dj-database-url>
endpoints_api_service:
name: "<PROJECT-ID>.appspot.com"
config_id: "<CONFIG-ID>"
然后我刚刚部署了应用程序
gcloud app deploy
现在,该应用程序已成功部署,但行为异常。所有应该返回 200 响应的请求仍然会引发 CORS 错误,但返回 400 状态的请求确实有效。
例如 - 注册 API 需要这些字段 - 电子邮件、密码 1、密码 2,其中密码 1 应与密码 2 相同。现在,当我发送正确的参数时,我会收到 HTTP 502 提示
请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin {origin-url} 不允许访问。响应的 HTTP 状态代码为 502
但是当我发送密码 1 与密码 2 不同时,我会收到 HTTP 400 响应,我确信该响应来自我的代码,因为如果密码 1 和密码 2 不匹配,响应是用代码编写的字典。同样在这种情况下,标头的 Access-Control-Allow-Origin 为 * 但在前一种情况下,这是不正确的
我还检查了我的 nginx 错误日志,上面写着
*27462 上游在读取响应头时过早关闭连接
我在这里做错了什么? 这是在 GAE 中启用 CORS 的正确方法吗?
【问题讨论】:
标签: django google-app-engine nginx http-status-code-502