使用从通过 golang 提供的 HTML 文件中获取来发送请求

问题描述 投票:0回答:1

我使用以下代码来提供 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-server 提供服务时则不然。

这是获取请求:

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).
javascript go fetch-api
1个回答
1
投票

您需要包含 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)
}
© www.soinside.com 2019 - 2024. All rights reserved.