首页 > 解决方案 > 为什么我的 Google Cloud Run 服务器返回 CORS 错误?

问题描述

我在 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)
}

标签: gogoogle-cloud-run

解决方案


请从官方文档中查看此示例:

// 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标头。


推荐阅读