Node.js表达app.get()奇怪的行为

时间:2017-06-22 11:50:54

标签: javascript node.js express

我对Express中的app.get()有疑问。只要路径末尾有.html,就不会调用该函数。在下面的代码段中,如果我尝试转到"test",则会将/random/example写入控制台,但在我转到/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");
})

1 个答案:

答案 0 :(得分:0)

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

如果您想让代码进行静态处理,则需要在设置静态处理之前定义路由。那么你的路由就是有效的中间件,可以在调用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中提到了Middleware callback function examples的链接。

注意:如果您只想将index.html发送到浏览器,则无需执行此操作。如果要在将请求交给静态文件处理之前挂钩请求,则只需要执行此操作。

相关问题