Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Putting JS obejct to res.JSON( ) is okay?

I’m trying to use fetch as a get method. And I got to know that it doesn’t matter if I send JS object or JSON by res.send.
So it doesn’t matter even if i put JS object to response.JSON() ??

this is react code

useEffect(()=>{
        fetch(`https://qwerasdfzxcvqwerasdfzxcv.run.goorm.io/user/${finalCode}`)
        .then(response=>response.json())      
        .then(data=>console.log(data))
        .catch(error=>console.log(error))
    },[finalCode])

below is server code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.get("/user/:code", function (req, res) {
    res.header("Access-Control-Allow-Headers","https://reactproject-oxzef.run.goorm.io")
    console.log("worked")
    
    Id.find({code:req.params.code}).lean().exec(function(err,docs){
        res.send(JSON.stringify(docs));
        res.send(docs);
        ****** these two line gives me same result.
    })
    
});

>Solution :

tl;dr: It does matter.


Look at the documentation for send.

The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.

So in one example (res.send(JSON.stringify(docs));) you pass it a string and in the other (res.send(docs);) you pass it whatever docs is which I assume is an object.

So both these data types are allowed however:

it automatically assigns the Content-Length HTTP response header field

and

When the parameter is a String, the method sets the Content-Type to “text/html”:

and

When the parameter is an Array or Object, Express responds with the JSON representation:

This means that when you pass it a string (res.send(JSON.stringify(docs));) Express will tell the browser that it an an HTML document which is wrong.

With your particular client-side code you are ignoring the content-type and parsing it as JSON regardless, but many systems do not, so you should not do that.

Examples of such systems include axios (which parses automatically) and the Network tab of your browser’s developer tools which is a useful way to debug data and can display JSON in parsed form if it knows it is JSON.


If you want to send JSON then pass your object to send. You could pass your object to the json method instead if you wanted to be explicit.

  • res.send(docs);
  • res.json(docs);
  • res.send(JSON.stringify(docs));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading