Good practice to handle useless response in express js/nodejs?

Viewed 91

Am using express js on node for my api service ! In which am using sequelize for query handling purposes !

So in some usecase like creating record, or updating record its simply returning "1" or sometimes nothing !

In this case , am just using

res.sendStatus(200);

or sometimes

res.send("success");

Is there any better way or this is the correct way to handle ? Or should in need .end() in order to end the process ??

which is a good way to handle these kind of useless responses which we dont need to send back ?

3 Answers

Usually a json is send back to the client with different information in it that lets the client-side know that the operation that they request through the api is successfull or failed. for e.g. here, you can define a standard json response like this

//in case of success of the request
{
   requestStatus: 1,
   ...other data if you want to like new Id of the created data/updated data or info about it if you want or depending upon use case
}

or

// in case of failure of the request
{
   requestStatus: 0,
   ...other data if you want to like reason for failure, error message or depending upon your use case
}

Just add this line of code, should be fine:

//For all bad endpoints
app.use('*', (req, res) => {
    res.status(404).json({ msg: 'Not a good endpoint, why are you here? Go play FIFA.'})
})

If you want you can generate an error HTML file, but since it's back-end, JSON format is strongly suggested. You can also add success: false for more clarity.

Related