go - 为什么我的 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)
}
解决方案
请从官方文档中查看此示例:
// 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
标头。
推荐阅读
- python - 如何选择对列表中的元组进行排序,以便在不使用 sorted 函数的情况下按字母倒序对元组进行排序
- python - 弹跳海龟功能但不运行
- c# - User.FindFirst(ClaimTypes.NameIdentifier) 从前端(Angular)调用时不检索任何内容
- c# - ASP.NET Core MVC 无法绑定复选框列表
- verilog - 以类成员为驱动程序的网络连续分配
- android - 如何将文本放入颤动的滑动器中?
- r - R 中两个变量的唯一组合(dplyr::distinct 不起作用)
- amazon-web-services - Terraform for AWS:根据 beanstalk 实例的 AZ 传递特定的资源地址
- excel - 查找具有单元格匹配范围值的所有行,复制到按值命名的新工作表
- python - 如何在python中识别字符串和字母数字字符串?