简体   繁体   English

node-express 如何在 URL 查询字符串中传递 DATE 参数以及如何解析它

[英]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.我有一个基于 Angular 2 构建的应用程序,该服务发送 http 请求以从 oracle DB、usind node-oracle db 和 express 框架中获取数据。 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.我已经使用 express 构建了 rest api,现在我需要在请求参数中传递 DATE,并且 express 必须解析它并发送响应。 How can i pass the DATE in query param and how i can parse that in express rest api.我如何在查询参数中传递 DATE 以及如何在 express rest api 中解析它。

Dates are one of only javascript types that don't get stored when you Stringify an object. 日期是当字符串化对象时不会存储的唯一javascript类型之一。

You can see Issues with Date() when using JSON.stringify() and JSON.parse() for more info. 使用JSON.stringify()和JSON.parse()时,您可以看到Date()的问题,以获取更多信息。

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 如果您只寻找日期,可以将其分为3个参数

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 您可以制作一个中间件来测试日期格式的字符串,然后使用JSON.parse reviver函数作为第二个参数将其转换为日期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' 通过iso格式传递日期'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. 我写了一系列有关日期的文章 ,内容涵盖了它们在客户端,中间层和Oracle数据库之间移动时发生的情况。 Here's the part that touches on node-oracledb . 是涉及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. Peter的答案已经涵盖了在字符串化后,从来自客户端的ISO 8601字符串中解析日期。 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. 我还要补充一点,如果将日期插入DATE或TIMESTAMP列中,则要确保连接到Oracle时的正确时区。 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:要扩展Peter 所写的内容,需要在 express.json() 中添加 reviver 函数,如下所示:

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 .感谢 Ben Nadel 在这里发表的出色文章。 The functions above are from his article.上面的函数来自他的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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