![](/img/trans.png)
[英]node.js & express: for loop and `app.get()` to serve articles
[英]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!')
});
注意:如果只希望将index.html
传递到浏览器,则不需要这样做。 仅当您要在转交给静态文件处理之前挂接到请求时才需要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.