[英]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.