首页 > 解决方案 > NodeJS 和 console.log 没有记录

问题描述

所以,自从我使用 node 以来,这是一个很热的时刻,我不能为我的生活,理解为什么这不起作用。

const body_parser = require("body-parser");
var express = require("express");
var app = express();

app.use("/", express.static(__dirname +  "/Contents/"));

app.get("/", function(req, res) {
    //Why wont this log to my terminal when a user visits the site?
    console.log("log it pleaseeeeeeeeee");
});

app.listen(5004, () => {
   console.log("server up and listening on port 5004");
});

每次用户访问该站点时,我都会尝试将“Log it Pleaseeeee”记录到运行我的nodejs应用程序的终端中。为什么这行不通?

标签: javascriptnode.jsexpress

解决方案


对于端点,您不能有 2 个单独的处理程序,在您的情况下为“/”

要实现你想要的,你必须提供一个中间件功能。

express将根据第二个参数的类型知道要做什么。中间件函数需要 3 个参数;最后一个是回调,所以它知道你什么时候准备好。

您应该通过将get函数移动到函数中并包括回调参数来更改代码,app.use('/', ...)如下所示:

const body_parser = require("body-parser");
var express = require("express");
var app = express();

app.use("/", function(req, res, callback) {
   console.log("log it pleaseeeeeeeeee");
   callback()
}, express.static(__dirname +  "/Contents/"));

/** GET RID OF THIS
app.get("/", function(req, res) {
   //Why wont this log to my terminal when a user visits the site?
   console.log("log it pleaseeeeeeeeee");
});
*/

app.listen(5004, () => {
   console.log("server up and listening on port 5004");
});

推荐阅读