Golang 标准 http 包 cors 问题

Golang standard http package cors issue

我在 server-side 上使用 built-in HTTP 包,但无法解决本地计算机上的 cors 问题。我的服务器正在向 front-end.

发送 JSON 响应

我试过在我的处理程序函数中设置 headers,如下所示,但没有成功:

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请求front-end:

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.

Server-side代码:

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

添加 w.Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers") 解决了问题。