繁体   English   中英

如何在AppEngine中为我的REST API启用单个网站的CORS

[英]How to enable CORS for a single website for my REST API in AppEngine

我在灵活的环境中在Appengine中拥有一个API。 它不支持CORS。 我相信是因为默认情况下它不支持

After ESP 1.0 is released on January 2, 2017, all Flexible Environment API deployments will feature the new version of ESP and will automatically disallow CORS requests by default. App Engine applications are automatically redeployed every 7 days, so sometime in the 7 days following the release of ESP 1.0, your app will be restarted with the latest version and will automatically be protected from unintended cross origin sharing.

If you are using Flexible Environments and would like to continue to allow CORS requests, you must add the "x-google-endpoints" snippet above to your API configuration (aka OpenAPI specification aka Swagger file). If you are relying on CORS, we recommend that you add the snippet as soon as possible and redeploy your service using the following command to avoid service interruption. Then you will not see changed behavior when the new version of ESP rolls out.

该页面告诉我设置allowCors = True并在我的后端代码中实现支持(这是否意味着我的main.go?) https://cloud.google.com/endpoints/docs/openapi/openapi-extensions

该页面告诉我在ESP中添加一些代码,但是我不确定它的含义-在我的openapi swagger文件中? https://cloud.google.com/endpoints/docs/openapi/specify-proxy-startup-options#adding_cors_support_to_esp

此页面https://enable-cors.org/server_appengine.html告诉我将这段代码添加到main.go中,但这意味着什么?

func doGet(w http.ResponseWriter, r *http.Request) {
  w.Header().Add("Access-Control-Allow-Origin", "*")
  w.Header().Add("Content-Type", "text/csv")
  fmt.Fprintf(w, csvData)
}

我正在努力寻找直接的步骤,以在我的AppEngine API上为一个网站启用CORS支持。 有人可以支持吗?

谢谢 :)

实现此目的最直接的方法是在OpenAPI文档的顶层添加x-google-extension

swagger: "2.0"
host: "my-cool-api.endpoints.my-project-id.cloud.goog"
x-google-endpoints:
- name: "my-cool-api.endpoints.my-project-id.cloud.goog"
  allowCors: True

在您找到的第一个链接中有关于此的更多信息。

关于您的问题:

此页面https://enable-cors.org/server_appengine.html告诉我将这段代码添加到main.go中,但这意味着什么?

func doGet(w http.ResponseWriter, r *http.Request) {
  w.Header().Add("Access-Control-Allow-Origin", "*")
  w.Header().Add("Content-Type", "text/csv")
  fmt.Fprintf(w, csvData)
  }

该段代码将在接收到GET请求时添加CORS标头。

编辑:

需要澄清的是,在Cloud Endpoints中启用CORS仅会允许请求到达您的后端,但是您必须处理后端代码中的访问限制。

由于您希望将CORS限制为仅一个网页,因此代码如下所示:

func doGet(w http.ResponseWriter, r *http.Request) {
      w.Header().Add("Access-Control-Allow-Origin", "https://www.example.com")
      w.Header().Add("Content-Type", "text/csv")
      fmt.Fprintf(w, csvData)
      }

在此示例中,仅允许使用网站https://www.example.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM