gpt4 book ai didi

javascript - 在 NodeJs 中存储上次收到的 REST 调用的日期/时间

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:47 25 4
gpt4 key购买 nike

我已经在 NodeJs 中编写了一个 REST API Connect-rest我想知道如何存储上次通话的日期和时间。

这是 GET url 调用

http://localhost:8080/api/books/metadata?id=12

过滤此 ID 的代码片段

module.exports.getItem = function(callback, id) {

var searchLetter = new RegExp(id, 'i');

//would like to record date/time the last time this call was made to this ID/row
//return the date/time back in the callback method
var row = items.filter(function(itemList) {
return searchLetter.test(itemList.asname);
});

return callback(null, {items: row, matches: row.length}, {headers: {'Content-type': 'application/json'}});
};

最佳答案

您可以在设置服务器时添加要与任何 api 调用一起使用的“全局路由”(即,如果您使用的是 Express 或 Restify 或类似工具):

app.use(function (req, res, next) {
console.log( "Got a request at " + new Date() ); //might want to format date
});

(请求参数可能已经存储了时间。)

其中一些框架将有一个“after”事件,该事件在请求完全处理后触发(因此此日志记录并不是真正的链的一部分)。就像来自 Restify 的这个示例一样,我在其中构建了自定义日志消息:

server.on( 'after', function logRequest( req, res, route, error ) {

var latency = res.get( 'Response-Time' );
if ( typeof( latency ) !== 'number' )
latency = Date.now() - req._time;

var obj = {
userAgent: req.headers[ 'user-agent' ],
url: req.url,
method: req.method,
statusCode: res.statusCode,
req_id: req.getId()
};
obj.latency = latency;
server.log.info( obj );
} );

在此示例中,我使用 Restify 的日志记录中间件,但您可以使用自己的记录器、console.log、附加到文件等。

关于javascript - 在 NodeJs 中存储上次收到的 REST 调用的日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com