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)

2
  • 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! Commented Dec 30, 2019 at 0:50
  • Does this answer your question? How to get JSON from URL in JavaScript? Commented Dec 30, 2019 at 1:08

2 Answers 2

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)
    })
  }
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Remove no-cors and try to add cors headers to express reponse: stackoverflow.com/a/45697474/5601899 stackoverflow.com/a/18311469/5601899
0

For return a json replace

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

for

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.