Home > Enterprise >  What would happen if i send a json file using res.send instead of res.json?
What would happen if i send a json file using res.send instead of res.json?

Time:12-10

We have a method res.json to send file in NodeJs but what would happen if we send a json file using res.send. What will be the consequences and why should we avoid doing this thing?

CodePudding user response:

I assume you are talking about ExpressJS:

Whenever an Express application server receives an HTTP request, it will provide the developer with an object, commonly referred to as res. For example,

Example

app.get('/test', (req, res) => {
   // use req and res here
})

The res object basically refers to the response that'll be sent out as part of this API call.

res.send:

The res.send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.

res.json:

The res.json function on the other handsets the content-type header to application/JSON so that the client treats the response string as a valid JSON object. It also then returns the response to the client.

conclusion:

With res.send you have to take care of converting it to a JSON object if needed, whereas with res.json this is done automatically.

CodePudding user response:

from express documentation:

res.json([body])

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.

res.send([body])

Sends the HTTP response.

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

This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.

When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined.

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

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

  • Related