【问题标题】:Why is my Google Cloud Run server returning a CORS error?为什么我的 Google Cloud Run 服务器返回 CORS 错误?
【发布时间】:2020-08-02 09:53:54
【问题描述】:

我在 go 中创建了一个后端,并使用 Google Cloud Run 进行了部署。现在我正在尝试从本地托管的网站 ping 它,但随后我收到了类似的 CORS 错误

type: "cors"
url: "https://abc.a.run.app/do-a"
redirected: false
status: 500
ok: false
statusText: ""
headers: Headers {}
body: (...)
bodyUsed: false

这些是我在 go 中的 http 处理函数中设置的标头。

w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

我的处理函数被路由

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
    http.HandleFunc("/do-a", endpoints.DoA)
    err := http.ListenAndServe(":"+port, nil)
    handle(err)
}

【问题讨论】:

  • 看起来您的原始配置有误。 w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000") 将 localhost:3000 更改为您正在使用的 URL https://....run.app
  • 那行不通。 http://localhost:3000 是我正在拨打电话的网站的网址。使用"*" 也不起作用
  • 请勿发布代码、数据、错误消息等的图片 - 将文本复制或输入到问题中。 How to Ask
  • 你是如何路由到处理函数的?您可以在问题中添加该示例代码吗?原因是如果 OPTIONS 请求的标头未正确处理,您可能会收到 CORS 错误。
  • 选项请求 curl -i -X OPTIONS https://abc.a.run.app/do-a 到您的后端应用程序的输出是什么?

标签: go google-cloud-run


【解决方案1】:

请查看官方文档中的this 示例:

// Package http provides a set of HTTP Cloud Functions samples.
package http

import (
        "fmt"
        "net/http"
)

// CORSEnabledFunctionAuth is an example of setting CORS headers with
// authentication enabled.
// For more information about CORS and CORS preflight requests, see
// https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.
func CORSEnabledFunctionAuth(w http.ResponseWriter, r *http.Request) {
        // Set CORS headers for the preflight request
        if r.Method == http.MethodOptions {
                w.Header().Set("Access-Control-Allow-Credentials", "true")
                w.Header().Set("Access-Control-Allow-Headers", "Authorization")
                w.Header().Set("Access-Control-Allow-Methods", "POST")
                w.Header().Set("Access-Control-Allow-Origin", "https://example.com")
                w.Header().Set("Access-Control-Max-Age", "3600")
                w.WriteHeader(http.StatusNoContent)
                return
        }
        // Set CORS headers for the main request.
        w.Header().Set("Access-Control-Allow-Credentials", "true")
        w.Header().Set("Access-Control-Allow-Origin", "https://example.com")
        fmt.Fprint(w, "Hello World!")
}

从您发布的代码中,我无法判断您是否检查了预检请求并设置了 Access-Control-Allow-Methods 标头。

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2020-07-17
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多