Golang standard http package cors issue

Issue

I’m using the built-in HTTP package on my server-side and I couldn’t resolve the cors issue on my local machine. My server is sending JSON responses to the front-end.

I’ve tried setting headers in my handler func like below, but it didn’t work:

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", "*")

The post request front-end:

axios.post('localhost:8080/', {
  name: 'test'
  
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

The error message:

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 code:

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

Solution

adding 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") solved the issue.

Answered By – Berke Kaan Cetinkaya

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.