use*_*882 2 node.js express angular
我有一个基于 angular 2 的应用程序,该服务发送 http 请求以从 oracle DB、usind node-oracle db 和 express 框架获取数据。我已经使用 express 构建了 rest api,现在我需要在请求参数中传递 DATE,并且 express 必须解析它并发送响应。我如何在查询参数中传递 DATE 以及如何在 express rest api 中解析它。
小智 7
使用iso格式'yyyy-mm-dd'传递日期
const date = new Date();
http.get(`url/test?date=${date.toISOString()}`
Run Code Online (Sandbox Code Playgroud)
在快递方面
app.get(/test', async function(req, res) {
const dateInServer = newDate(req.query.date);
Run Code Online (Sandbox Code Playgroud)
});
日期是在对对象进行字符串化时唯一不会存储的 JavaScript 类型之一。
您可以查看使用 JSON.stringify() 和 JSON.parse() 时的 Date() 问题 以获取更多信息。
您的选择是:
如果您只想查找日期,可以将其分为 3 个参数
var valueToSend = {
date: {
day: date.getDate(),
month: date.getMonth(),
year: date.getYear()
}
Run Code Online (Sandbox Code Playgroud)
然后在快递方面
new Date(req.body.year, req.body.month, req.body.date)
Run Code Online (Sandbox Code Playgroud)
这种方法的优点是易于验证,并且您只需发送所需的信息。缺点是代码比较多
您可以制作一个中间件来测试日期格式的字符串,并使用 JSON.parse reviver 函数作为第二个参数将其转换为日期https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/JSON/解析
例如
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15121 次 |
| 最近记录: |