Giving by example the GET route request below, both WORK. I am trying to understand their differences and which one is the best approach for doing this. Any comments on the 2 coding options, please?
Option 1
router.get("/", (req, res) => {
AddStudents.find({})
.then((data) => {
res.json(data);
})
.catch((error) => {
});
});
Option 2
router.get("/", async (req, res) => {
AddStudents.find({}, (err, result) => {
if (err) {
res.send(err);
}
res.json(result);
});
});
CodePudding user response:
res.json will convert the data to json format. So it will convert the data to
res.json: content-type: application/json
from
res.send: content-type: text/html
option 2
async
will automatically wrap the data in a promise so you dont have to do that.
So when an array is passed they return the same but if there are null or undefined values in the data the res.json will do explicit JSON conversion of them cuz aint valid json