节点响应优先级

时间:2019-07-09 07:00:29

标签: node.js

我的节点应用程序有问题。我在节点应用程序中使用express到服务器页面。但是它看起来像基本函数:

app.use(express.static('public'));
app.use(express.static('allure-report'));

app.get('/', (req, res) => {
    //myHtmlCode is read my fs from index.html
    //res.send(myHtmlCode);
    //res.render('index', { html: myHtmlCode })
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    res.write(myHtmlCode);
});

在所有这些情况下,节点将为公用文件夹内的index.html页面提供服务器。如果我从公用文件夹中删除index.html页面,它将从allure-report文件夹中处理index.html。

我如何告诉节点不要提供index.html文件,并在“ app.get('/',(req,res)=> {”)函数中提供动态内容? 它不适用于发送,呈现或写入。

如果index.html文件可用,则看起来该节点完全忽略该功能或路由“ /”。

看起来像这样

app.get('/', function(req, res) {

从不被调用。

1 个答案:

答案 0 :(得分:2)

app.get上方的app.use移动到请求处理程序中的下一个,如下所示:

app.get('/', function(req, res, next) { ...; next(); })    
app.use(express.static('public'));    
app.use(express.static('allure-report'));

Express按照您定义的顺序处理所有app.use的响应,因此express.static('public')express.static('allure-report')将首先处理响应,而不会您要运行的功能。

当您在响应处理程序中调用next()时,它将把请求传递给行中的下一个处理程序。