【发布时间】:2022-02-01 20:08:13
【问题描述】:
我在服务器端使用内置 HTTP 包,但无法解决本地计算机上的 cors 问题。我的服务器正在向前端发送 JSON 响应。
我尝试在我的处理程序 func 中设置标题,如下所示,但没有成功:
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Origin", "*")
post 请求前端:
axios.post('localhost:8080/', {
name: 'test'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
错误信息:
Access to XMLHttpRequest at 'localhost:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
服务器端代码:
func main() {
http.HandleFunc("/", HelloServer)
fmt.Println("Server started at port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
content, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println(err)
}
var file File
json.Unmarshal(content, &file)
// file name got here
path := fmt.Sprintf("./posts/%s.txt", file.Name)
textContentByte := readBlogFile(path)
jsonResp, err := json.Marshal(textContentByte)
if err != nil {
fmt.Println(err)
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.Write(jsonResp)
fmt.Println(string(jsonResp))
}
【问题讨论】:
-
回答你的问题并不容易,因为问题描述得不够好。你说你有一个“cors 问题”,但是你具体在做什么,你的 go 服务器在哪里,你看到了什么?也许您可以在问题中包含足够的信息,以便其他人可以重现该问题。
-
错误的一个可能原因是使用了
Set("Access-Control-Allow-Origin", "*")。"*"通配符只允许用于没有凭据的请求。如果请求正在发送凭据,那么您必须明确指定来源,而不是"*"。您可以从传入请求(处理程序的r *http.Request参数)中提取来源。见mdn。 -
@PaulHankin 感谢您的回复,我已经添加了更多详细信息
-
@BerkeKaanCetinkaya 如果将
axios.post('localhost:8080/'更改为axios.post('http://localhost:8080/'会发生什么? -
@mkopriva 没用