1

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.
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
zero_cool
  • 3,960
  • 5
  • 39
  • 54

1 Answers1

2
w.Header().Set("Access-Control-Allow-Origin", "*")    
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("content-type", "application/json") 

You can try to add them in the handleFunc

jiangyx3915
  • 119
  • 3