1

Here's what I did on the react end:

  componentDidMount(){
    console.log('zzzzzzzzzzz')
    fetch('http://localhost:5000/z', {mode: 'no-cors'}).then(res=>{console.log(res)
    this.setState(res)})
  }

Here's what I did with NodeJS + Express:

app.get('/z', (req, res)=>{
  console.log('requested')
  res.send({msg: "YEEEEHAW"})
})

The request does go through, but it's not what I wanted (the 'YEEEEHAW' is nowhere to be found in browser console):

Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
type: "opaque"
url: ""
redirected: false
status: 0
ok: false
statusText: ""
headers: Headers
__proto__: Headers
body: (...)
bodyUsed: false
__proto__: Response
type: (...)
url: (...)
redirected: (...)
status: (...)
ok: (...)
statusText: (...)
.......

What did I do wrong here? How can I fix it? (To be clear, I did look through + expand every expandable field in the logged object so I'm pretty sure I didn't miss it)

Stoodent
  • 155
  • 1
  • 9
  • 3
    If your server responds w JSON you need to add `.then(res => res.json())` before the `then` doing the `console.log`. Edit: The network tab does help a lot too! – Andre Nuechter Dec 30 '19 at 00:50
  • Does this answer your question? [How to get JSON from URL in JavaScript?](https://stackoverflow.com/questions/12460378/how-to-get-json-from-url-in-javascript) – Emile Bergeron Dec 30 '19 at 01:08

2 Answers2

4

To read response content, you can use res.json():

componentDidMount(){
    console.log('zzzzzzzzzzz')
    fetch('http://localhost:5000/z', {mode: 'no-cors'})
    .then(res=>res.json())
    .then(res=>{
        console.log(res)
        this.setState(res)
    })
  }
  • That looks like it'd work, but I got this error when I tried: 'Homepage.js:19 Uncaught (in promise) SyntaxError: Unexpected end of input'. Would you know why this is? – Stoodent Dec 30 '19 at 20:50
  • 1
    Remove no-cors and try to add cors headers to express reponse: https://stackoverflow.com/a/45697474/5601899 https://stackoverflow.com/a/18311469/5601899 – Alexander Vidaurre Arroyo Dec 30 '19 at 22:03
0

For return a json replace

res.send({msg: "YEEEEHAW"})

for

 res.json({msg: "YEEEEHAW"})