I am trying to declare a POST
method for a RESTful API using node and express. I need to accept the request body and write it onto a JSON file that I’m using to store my users data. I am using the fs
module to modify the JSON file.
I have written the same code with a slight difference in declaring the return statement.
Method 1-
app.post('/api/users', (req, res) => {
const body = req.body;
users.push(body)
fs.writeFile("./users.json", JSON.stringify(users), (err) => {
if (err) {
console.log(err)
}
return res.json({ status: 'success', data: body });
})
})
Method 2-
app.post('/api/users', (req, res) => {
const body = req.body;
users.push(body)
fs.writeFile("./users.json", JSON.stringify(users), (err) => {
if (err) {
console.log(err)
}
})
return res.json({ status: 'success', data: body });
})
As per what I understand, the return statement in Method 1 is meant for the callback
fn parameter of the fs
module. Whereas the return statement in Method 2 is explicitly defined for the request handler
fn for the POST
method. And res.send()
is used with the req. handler fn.
Is there any difference between these two methods? Which one is the correct way? Do they essentially perform the same function?