在 Express 中显示每个请求的日志时间?

Ade*_*uzi 5 javascript datetime node.js express momentjs

我这里有问题。我不知道为什么会这样。我将时间戳代码放在 Moment.js 库中,不仅是该库,最近我手动创建用于显示时间戳,但是当我发送请求时,时间没有更新。我把日期时间放在我的文件路径中。但这是在服务器文件中的工作。

所以例如

服务器.js

var express = require('express')
var app = express()
var moment = require('moment')

app.use(function(req, res, next){
  console.log(moment().format('HH:mm:ss') + ' From server.js') //Showing time now
  next();
  })

app.use('/', index)
app.listen(8001)
Run Code Online (Sandbox Code Playgroud)

路线/ index.js

var express = require('express')
var app = express()
var moment = require('moment')

app.use(function(req, res, next){
  console.log(moment().format('HH:mm:ss') + ' From server.js') //Showing time now
  next();
  })

app.use('/', index)
app.listen(8001)
Run Code Online (Sandbox Code Playgroud)

我第一次开始测试我的代码 GET localhost:8001/

我的系统时间显示为 16:20:51

[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
16:20:51 From Server.js
16:20:51 From routes/index.js
Run Code Online (Sandbox Code Playgroud)

第二个请求我的系统时间显示 16:22:52

[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
16:22:52 From Server.js
16:20:51 From routes/index.js
Run Code Online (Sandbox Code Playgroud)

不,第二个请求仍然从第一个请求中获取现有的时间日志,这只发生在路由中。但是在 server.js 中很好地工作

是否因为函数外的可变时间戳而发生?但是当我在没有变量的情况下运行时,它起作用了。

router.get('/', function(req, res){
  console.log(moment().format('HH:mm:ss') + ' From routes/index.js')
})
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?谢谢

Laz*_*ert 3

You cache the timestamp value.

Modify your route file this way:

var express = require('express')
var app = express()
var router = express.Router()
var moment = require('moment')

router.get('/', function(req, res){
  var timestamps = moment().format('HH:mm:ss')
  console.log(timestamps + ' From routes/index.js')
})

module.exports = routes
Run Code Online (Sandbox Code Playgroud)

You have to understand that file is included once the application started and until it is running. The only part is called from time to time here is the function handler of the route:

function(req, res){
  var timestamps = moment().format('HH:mm:ss')
  console.log(timestamps + ' From routes/index.js')
}
Run Code Online (Sandbox Code Playgroud)