英文:
Send request using fetch from HTML file served through golang
问题
我正在使用以下代码来提供一个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文件包含一个使用fetch来获取一些数据的JavaScript文件。当通过Apache服务器提供时,这个工作正常,但是通过Go服务器提供时却不行。
这是fetch请求的代码:
const fetchSettings = {
method: "POST",
body: JSON.stringify(requestBody),
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch("https://some.url", fetchSettings);
以下是我得到的错误信息:
跨域请求被阻止:同源策略禁止读取远程资源 https://some.url(原因:缺少CORS头部‘Access-Control-Allow-Origin’)。
跨域请求被阻止:同源策略禁止读取远程资源 https://some.url(原因:CORS请求未成功)。
英文:
I am using the following code to serve a HTML file.
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)
}
This HTML file includes a JavaScript file that uses fetch to retrieve some data. This works fine when serving through apache, but not when served through the Go-server.
This is the fetch-request:
const fetchSettings = {
method: "POST",
body: JSON.stringify(requestBody),
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch("https://some.url", fetchSettings);
And here is the error I'm getting:
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).
答案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)
}
希望对你有帮助!
英文:
You need to include an Access-Control-Allow-Origin header:
rw.Header().Set("Access-Control-Allow-Origin", "*")
That one allows all origins, you can read more here: https://perennialsky.medium.com/handle-cors-in-golang-7c5c3902dc08
Here is how it would fit in your code:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论