使用从golang提供的html文件中获取的内容发送请求

vaqhlq81  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(360)

我使用以下代码来提供一个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).
uxh89sit

uxh89sit1#

您需要包括一个访问控制允许源标题:

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

相关问题