简体   繁体   中英

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

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.

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

eg

 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;
}

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);

});

I wrote a series on dates that covers what happens as they move between clients, mid-tiers, and Oracle Database. Here's the part that touches on node-oracledb . You might find some of that info useful.

Peter's answer already covers parsing the date from an ISO 8601 string that comes from the client after being stringified. I'll add that you want to make sure the correct time zone when connecting to Oracle if the date is being inserted into DATE or TIMESTAMP columns. The doc covers this as well.

To expand on what Peter wrote , one would need to add the reviver function within express.json(), like so:

app.use(express.json({ reviver: dateReviver }));

// I am a JSON.parse() reviver that will parse serialized Date objects back into actual
// Date objects.
// --
// CAUTION: This gets called for every single value in the deserialized structure.
function dateReviver(key, value) {
  if (isSerializedDate(value)) {
    return new Date(value);
  }

  // If it's not a date-string, we want to return the value as-is. If we fail to return
  // a value, it will be omitted from the resultant data structure.
  return value;
}

// I determine if the given value is a string that matches the serialized-date pattern.
function isSerializedDate(value) {
  // Dates are serialized in TZ format, example: '1981-12-20T04:00:14.000Z'.
  var datePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;

  return isString(value) && datePattern.test(value);
}

// I determine if the given value is a String.
function isString(value) {
  return {}.toString.call(value) === "[object String]";
}

Credit to Ben Nadel for his excellent article here . The functions above are from his article.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM