javascript - 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应用程序的终端中。为什么这行不通?
解决方案
对于端点,您不能有 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");
});
推荐阅读
- c# - 递归创建 XML 树父命名空间时丢失
- angular - ng2-smart-table 中的复选框
- amazon-redshift - 如何在框架子句redshift window_functions中将列字段指定为偏移量?
- webpack - Angular 6 将组件构建到单独的 Javascript 文件中
- c# - 更改方法后如何解决int值重置
- nuget - MyGet - 强制 nuget push 推送最新包
- graphql - 如何在保证订阅准备就绪的情况下执行突变?
- python - Python - 从 tkinter 按钮单击终止程序?
- types - Roslyn CodeFix Provider (VS2015):如何获取类属性/字段类型
- php - Modbus Php 读取 int16