Golang中如何处理'Access-Control-Allow-Origin'问题
Golang中如何处理’Access-Control-Allow-Origin’问题 请求的资源上不存在’Access-Control-Allow-Origin’头部。因此不允许源’null’进行访问。
4 回复
非常感谢。
更多关于Golang中如何处理'Access-Control-Allow-Origin'问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
如果您更喜欢易于集成到HTTP路由器中的实现,请查看这个包。
Access-Control-Allow-Origin 响应头指示是否可以将响应与给定来源或所有来源的资源共享,请查看 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin,即:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
其中 origin 是 URI。
要在 Go 中设置请求头,请使用 Header.Add:
req.Header.Add("Access-Control-Allow-Origin", "*")
或
req.Header.Add("Access-Control-Allow-Origin", uri)
希望这能解答您的问题。
在Golang中处理CORS(跨域资源共享)问题,可以通过设置Access-Control-Allow-Origin头部来解决。以下是一个使用标准库net/http的示例:
package main
import (
"net/http"
)
func main() {
// 创建HTTP服务器
http.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
// 设置CORS头部
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// 处理预检请求
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
// 正常处理请求
w.Write([]byte("响应数据"))
})
http.ListenAndServe(":8080", nil)
}
对于更复杂的CORS配置,推荐使用第三方库github.com/rs/cors:
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("响应数据"))
})
// 配置CORS
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000", "https://example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowCredentials: true,
})
handler := c.Handler(mux)
http.ListenAndServe(":8080", handler)
}
第一个示例设置了允许所有来源(*),第二个示例使用cors库提供了更精细的控制,包括指定允许的来源、方法和头部。

