簡體   English   中英

node-express 如何在 URL 查詢字符串中傳遞 DATE 參數以及如何解析它

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

我有一個基於 Angular 2 構建的應用程序,該服務發送 http 請求以從 oracle DB、usind node-oracle db 和 express 框架中獲取數據。 我已經使用 express 構建了 rest api,現在我需要在請求參數中傳遞 DATE,並且 express 必須解析它並發送響應。 我如何在查詢參數中傳遞 DATE 以及如何在 express rest api 中解析它。

日期是當字符串化對象時不會存儲的唯一javascript類型之一。

使用JSON.stringify()和JSON.parse()時,您可以看到Date()的問題,以獲取更多信息。

您可以選擇以下兩種方式之一:

分割輸入日期

如果您只尋找日期,可以將其分為3個參數

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

然后在快遞方面

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

這種方法的優點是易於驗證,並且只發送所需的信息。 缺點是它是更多的代碼

在快遞方面使用正則表達式

您可以制作一個中間件來測試日期格式的字符串,然后使用JSON.parse reviver函數作為第二個參數將其轉換為日期https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects / JSON / parse

例如

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

通過iso格式傳遞日期'yyyy-mm-dd'

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

在快遞方面

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

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

});

我寫了一系列有關日期的文章 ,內容涵蓋了它們在客戶端,中間層和Oracle數據庫之間移動時發生的情況。 是涉及node-oracledb的部分 您可能會發現其中一些有用的信息。

Peter的答案已經涵蓋了在字符串化后,從來自客戶端的ISO 8601字符串中解析日期。 我還要補充一點,如果將日期插入DATE或TIMESTAMP列中,則要確保連接到Oracle時的正確時區。 該文檔也涵蓋了這一點。

要擴展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]";
}

感謝 Ben Nadel 在這里發表的出色文章。 上面的函數來自他的文章。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM