如何在此代码片段中尝试在控制台中记录日期?

How do I log the dates in the console as I am trying to do in this code snippet?

我正在尝试像这样控制日志日期、请求方法和请求 URL。这是错误的吗?我该如何做对?

let express = require("express");
let app = express();

app.use(function(req, res, next) {
    console.log("${new Date()} - ${req.method} request for ${req.url}");
    next();
});

app.use(express.static("../static"));

app.listen(8000, function() {
    console.log("Serving static on 8000")
});

目前输出只是

Serving static on 81
${new Date()} - ${req.method} request for ${req.url}
${new Date()} - ${req.method} request for ${req.url}
${new Date()} - ${req.method} request for ${req.url}
${new Date()} - ${req.method} request for ${req.url}

我在 node.js 和一台 Linux(Fedora) 机器上使用 express。

在 Linux 中执行此操作的正确方法是:

 console.log(new Date(), "-", req.method, "request for", req.url);

这应该可以解决问题。

要使用模板文字,您需要将双引号(") 替换为反引号(`)。之后,您的 console.log 应该如下所示:

console.log(`${new Date()} - ${req.method} request for ${req.url}`);

查看有关模板文字的更多信息here