Reputation: 81
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(¶ms)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%v", err)
return
}
// somthing else here
})
what am I doing wrong?
Upvotes: 0
Views: 563
Reputation: 81
In the end, I was missing a header.
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
credit goes to @mkopriva!
Upvotes: 1