I'm running a react app on localhost:3000
, and a go server on localhost:8000
.
When I make a request
from the client using fetch
- the response is opaque so I'm not able to access the data.
How do I make a valid cross-origin request?
client:
componentWillMount() {
const url = 'https://localhost:8000/api/items'
fetch(url, { mode: 'cors' })
.then(results => {
return results.json()
}).then(data => {
let items = data;
this.setState({items})
})
}
server:
func GetItems(w http.ResponseWriter, r *http.Request) {
items := getItems()
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(items)
}
From what I've read - it's expected that requests made across resources should be opaque - but for local development - how do you get access to the JSON?
After looking at the definitions for request types I found this:
cors: Response was received from a valid cross-origin request. Certain headers and the body may be accessed.
I think I need to set up a valid cross-origin request.
I got it!
This question helped resolve how to set up CORS in golang: Enable CORS in Golang
3 key things here:
Set the mode in the client request to
cors
Set the
Access-Control-Allow-Origin
header on the server to*
- Call
.json()
on the result in the client, and in a following promise you can access the data.