I am trying to render an alternative response to my express.js route when a date value in the parameter ends up being invalid. When I see an invalid date the value ends up being null so in my if statement in the middleware I test for a truthy value and if it is not truthy i serve up an alternative response.
What I get is the true value even though the value of the date is null. Here is an example:
api/timestamp/hello is my route.
A valid date should look like this: {"unix":1546214400000,"utc":"Mon, 31 Dec 2018 00:00:00 GMT"}
An invalid date like 'hello' should look like this {'error': 'Invalid Date'}
The code returns the correct value if the date is valid, but if the date is invalid I get {"unix":null,"utc":"Invalid Date"}
instead of {'error': 'Invalid Date'}
Below is the code.
app.get('/api/timestamp/:date', (req,res) => {
let date = new Date(req.params.date);
if (date === null) {
res.send({'error': 'Invalid Date'});
} else {
let unix = date.getTime();
let utc = date.toUTCString();
res.send({unix, utc});
}
});
I'm relatively new to express and Node.js for that matter. Any thoughts on why the null value is not being recognized?