繁体   English   中英

Node.js表达app.get()异常行为

[英]Node.js express app.get() odd behaviour

我对Express中的app.get()有疑问。 每当路径末尾带有.html时,似乎都不会调用该函数。 在下面的代码段中,如果我尝试转到/random/example ,则将"test"写入控制台,但当我转到/index.html时,则不会。 那么,当我转到主页时如何使其调用函数? (我尝试使用“ /”作为路径,它也不起作用。)

app.use(express.static("public"))

app.get('/index.html',function(req,res){
   console.log("test");
})

app.get('/random/example',function(req,res){
   console.log("test");
})

您看不到/index.html"test" ,因为静态文件处理正在为您处理该过程。

如果要调用代码进行静态处理,则需要在设置静态处理之前定义路由。 这样,您的路由便是有效的中间件,并且可以在调用next之前进行处理,以传递到下一层处理,这将是静态处理:

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

// Set this up first
app.get('/index.html',function(req,res, next){
   console.log("test - /index.html");
   next(); // <== Let next handler (in our case, static) handle it
});

app.get('/random/example',function(req,res){
   console.log("test /random/example");
});

// Now define static handling
app.use(express.static("public"));

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
});

get提到了指向中间件回调函数示例的链接。

注意:如果只希望将index.html传递到浏览器,则不需要这样做。 仅当您要在转交给静态文件处理之前挂接到请求时才需要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM