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

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

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?

>Solution :

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

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.

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