ReactJS, Golang server CORS content-type trouble

Issue

So I’ve been trying to connect my reactJS local client to my Golang local server with a POST request, but I keep getting this error:

Access to fetch at ‘http://localhost:8080/’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

I’ve already tried to change the heathers on the server and client side multiple times, but I’ve got no luck so far. FYI everything works just fine in Postman.

This is my code on client side

const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                First: this.state.first,
                Second: this.state.second,
                Symbol: this.state.symbol,
                Date: this.state.date,
            })
        };
        fetch('http://localhost:8080/', requestOptions)
            .then(response => { return response.json() })
            .then(data => {
                this.setState({ result: data });
            })
        .catch(console.log)
}

and this is it on the server side

type Params struct {
    First string
    Second string
    Symbol string
    Date string
}

func main() {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

       if r.Method != http.MethodPost {
            fmt.Fprintf(w, "Hi there")
            return
        }


        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Content-Type", "application/json")

        var params Params
        err := json.NewDecoder(r.Body).Decode(&params)

        if err != nil {
            w.WriteHeader(http.StatusBadRequest)
            fmt.Fprintf(w, "%v", err)
            return
        }

        // somthing else here

    })

what am I doing wrong?

Solution

In the end, I was missing a header.

w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

credit goes to @mkopriva!

Answered By – iiiasminx

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.