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

Time:11-24

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

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.
    })
    
});

CodePudding user response:

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));

CodePudding user response:

res.json stringifies the object. This is perfectly fine and in fact encouraged.

From Express 4.x docs:

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

  • Related