gpt4 book ai didi

javascript - 路由时 express.js 不显示 console.log 消息

转载 作者:数据小太阳 更新时间:2023-10-29 04:30:44 26 4
gpt4 key购买 nike

注:我对表达很陌生

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

app.get('/', function(req, res) {
res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
var things = require('./things/things.js');

//both index.js and things.js should be in same directory
app.use('/things', things);
//Simple request time logger
app.use('/',function(req, res, next){
console.log("A new request received at " + Date.now());

//This function call is very important. It tells that more processing is
//required for the current request and is in the next middleware
//function/route handler.
next();
});

app.listen(3000);

我正在学习中间件功能,并尝试在转到 localhost:3000 时显示一条 console.log 消息,但我的控制台中没有显示任何内容,我在这里缺少什么?

最佳答案

问题是 Express 将请求按声明的顺序传递给中间件和路由处理程序。如果它们中的任何一个能够处理请求(通过发回响应),则不会调用任何其他匹配的中间件或稍后声明的路由处理程序。

这就是您的情况,您的中间件是在路由处理程序之后声明的。

尝试将你的中间件移到前面:

app.use('/',function(req, res, next){
console.log("A new request received at " + Date.now());
next();
});

app.get('/', function(req, res) {
res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});

var things = require('./things/things.js');

app.use('/things', things);

关于javascript - 路由时 express.js 不显示 console.log 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45528995/

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