我正在使用以下代码来提供HTML文件。
func main() {
http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/" {
path = "index.html"
}
http.ServeFile(rw, r, "./"+path)
})
http.ListenAndServe(":5555", nil)
}
这个HTML文件包括一个JavaScript文件,它使用fetch来检索一些数据。当通过apache提供服务时,这很好,但当通过Go服务器提供服务时就不行了。
这是提取请求:
const fetchSettings = {
method: "POST",
body: JSON.stringify(requestBody),
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch("https://some.url", fetchSettings);
这是我得到的错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.url. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.url. (Reason: CORS request did not succeed).
您需要包含Access Control Allow Origin标头:
rw.Header().Set("Access-Control-Allow-Origin", "*")
这个允许所有起源,你可以在这里阅读更多:https://perennialsky.medium.com/handle-cors-in-golang-7c5c3902dc08
以下是它如何适合您的代码:
func main() {
http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/" {
path = "index.html"
}
rw.Header().Set("Access-Control-Allow-Origin", "*")
http.ServeFile(rw, r, "./"+path)
})
http.ListenAndServe(":5555", nil)
}