簡體   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