vasansr / react-tutorial-mern

Build a complete React app, step-by-step with the MERN stack
https://hashnode.com/post/react-tutorial-using-mern-stack-ciiyus9m700qqge53mer0isxz
98 stars 28 forks source link

ParseJSON result of the API call first ? #4

Closed malikankit closed 7 years ago

malikankit commented 7 years ago

https://github.com/vasansr/react-tutorial-mern/blob/e61aac0385aeca338dfbc3c9533f1c087e8d2041/src/App.js#L93

@vasansr : Great tutorial!

Minor issue - This line works only if I wrap it with parseJSON first. this.setState({bugs: data}); vs this.setState({bugs: $.parseJSON(data)});

vasansr commented 7 years ago

Double-checked, the original code works without the parseJSON, provided the server is sending the correct information.

You may want to check if what the server is sending has the correct contentType header. If the server sends out the correct content-type header (application/json), jQuery will auto-parse the json. See http://api.jquery.com/jquery.ajax/ (search for section on dataType, you will find the following):

dataType (default: Intelligent Guess (xml, json, script, or html))

If by mistake you are using res.send(JSON.stringify(bugData)) in the server, this can happen because Express doesn't know you are sending out a json, so it will skip the application/json content-type header

Or, if you use res.json(JSON.stringify(bugData)) also this can happen because it is double-stringified even though the content type is application/json.

malikankit commented 7 years ago

You are right. Thanks for the detailed response!