app.use() 和 app.get() 之间的区别

Difference between app.use() and app.get()

var express = require('express'); 
var app = express(); 
var PORT = 3000; 
  
// This middleware will not allow the 
// request to go beyond it 
app.use(function (req, res, next) { 
    console.log("Middleware called") 
    next(); 
}); 
    
// Requests will never reach this route 
app.get('/user', function (req, res) { 
    console.log("/user request called"); 
    res.send('Welcome to GeeksforGeeks'); 
}); 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
}); 

你能解释一下“这个中间件不允许请求超出它”吗?事实上,输出是正确的,但为什么这样写呢? 代码取自geeksforgeeks

由于第一个中间件有next()调用,它肯定会把处理传递给下一步(即下一个合适的中间件函数),所以,看起来注释无效。

在控制台日志中,您应该至少看到 Middleware called 行。

app.use() 和 app.get() 有什么区别? 嗯,GET 是一种用于从服务器接收数据的 HTTP 方法。例如 HTML 页面。 但是中间件是在实际服务器方法之前调用的应用程序,您可以访问名为 next() 的东西以将请求传递到下一个路由。例如你可以定义一个中间件来检查用户登录,如果它已登录你可以将它传递给下一个路由。

关于该代码: 评论不对!由于中间件中使用了 next(),中间件将允许请求超出范围。