node-express how to pass DATE params in URL query string and how to parse that

17,580

Solution 1

pass the date with iso format 'yyyy-mm-dd'

const date = new Date();
http.get(`url/test?date=${date.toISOString()}`

in the express side

app.get(/test', async function(req, res) {

const dateInServer = newDate(req.query.date);

});

Solution 2

Dates are one of only javascript types that don't get stored when you Stringify an object.

You can see Issues with Date() when using JSON.stringify() and JSON.parse() for more info.

Your options here are either:

Split the date on input

If you are only looking for a date you can split it into 3 parameters

var valueToSend = {
  date: {
    day: date.getDate(),
    month: date.getMonth(),
    year: date.getYear()
}

Then on the express side

new Date(req.body.year, req.body.month, req.body.date)

The Pros of this approach is that is is easy to validate and you are only sending the info you need. The downside is that it is more code

Use Regex on the express side

You could make a middleware that tests for a date formatted string and convert it to a date using JSON.parse reviver function as the second parameter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

e.g.

 module.exports = (req, res, next) => {
     for (var bodyKey in req.body) {
         if (req.body.hasOwnProperty(bodyKey)) {
             req.body[bodyKey] = JSON.parse(req.body[bodyKey],dateTimeReviver);
         }
     }
     next();
 };

function dateTimeReviver(key, value) {
  var a;
    if (typeof value === 'string') {
        a = /[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z/.exec(value);
        if (a) {
            return new Date(a[0]);
        }
    }
    return value;
}
Share:
17,580
user2662882
Author by

user2662882

Updated on June 11, 2022

Comments

  • user2662882
    user2662882 almost 2 years

    I have an app built on angular 2, a service in that sending http request to fetch the data from oracle DB, usind node-oracle db and express framework. I have built rest api's using express, now i need to pass the DATE in request parameter and express has to parse that and send the response. How can i pass the DATE in query param and how i can parse that in express rest api.