ExpressJS send method
while I was learning NodeJS I saw this piece of code.
import express from 'express';
const app = express();
//routes
app.get('/', (req, res) => {
res.send('<h1>Hello World</h1>');
});
app.listen(3000, () => {
console.log('App is running on port 3000');
});
Now I thought what type of data can we send using the res.send().
With that in mind I started to explore the "res" object, then I came to know that we can send 'HTML', 'normal text', 'JSON', 'arrays', 'boolean values' etc... with the help of res.send() method.
app.get('/', (req, res) =>{
res.send('<h1>Hello World</h1>')
//we can send the response in the below formats
// use only of these ways in a function
res.send('Hello World') //-> string
res.send({message: 'Hello World'}) //-> object, will be converted to JSON
res.send([1, 2, 3, 4, 5]) //-> array
res.send(true) //-> boolean
res.send(null) //-> null
})
As you can see above, we always miss a lot of small details because in most Youtube tutorials we are taught about only one approach. If you go a little deep into the coding hole, then you unlock a lot of new approaches and solutions.
Thank you and I will let you read my mind again with a different topic. Until then keep exploring and keep learning.
Subscribe to my newsletter
Read articles from Sam directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Sam
Sam
I am final year B.Tech student, looking for a job and sharing knowledge and letting people read my mind.