Javascript 为什么斜杠URL与NodeJS中间件中的所有其他URL一起运行?

Javascript 为什么斜杠URL与NodeJS中间件中的所有其他URL一起运行?,javascript,node.js,express,Javascript,Node.js,Express,为什么输入http://localhost:3000/product在浏览器上,输出将同时是'/'和'/product'的输出 请看这个代码片段 const express = require('express'); const app = express(); // http://localhost:3000/product app.use('/product', (req, res, next)=>{ console.log('In product page');

为什么输入
http://localhost:3000/product
在浏览器上,输出将同时是
'/'
'/product'
的输出

请看这个代码片段

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


// http://localhost:3000/product
app.use('/product', (req, res, next)=>{
    console.log('In product page');
    res.send('<h1>Product Page</h1>');
});


// http://localhost:3000/
app.use('/', (req, res, next)=>{
    console.log('In main page');
    res.send('<h1>Main Page</h1>');
});


app.listen(3000);
const express=require('express');
常量app=express();
// http://localhost:3000/product
应用程序使用(“/产品”,(请求、回复、下一步)=>{
console.log(“在产品页面中”);
res.send(“产品页面”);
});
// http://localhost:3000/
应用程序使用(“/”,(请求、恢复、下一步)=>{
console.log(“在主页上”);
res.send(“主页”);
});
app.listen(3000);
此图像是我的应用程序的输出。


可能有多种原因。我现在想到的一个问题是浏览器请求
http://localhost:3000/
product.html
之后自动执行,这将触发
使用('/',…)
路由

也许您应该使用而不是,以避免每个路径上的“通配符”应该是404页面。

app.use()方法用于绑定应用程序级中间件。不适用于按预期接受GET请求

你应该使用

    // http://localhost:3000/product
    app.get('/product', (req, res)=>{
        console.log('In product page');
        res.send('<h1>Product Page</h1>');
    });


    // http://localhost:3000/
    app.get('/', (req, res)=>{
        console.log('In main page');
        res.send('<h1>Main Page</h1>');
    });
//http://localhost:3000/product
app.get(“/product”,(req,res)=>{
console.log(“在产品页面中”);
res.send(“产品页面”);
});
// http://localhost:3000/
应用程序获取(“/”,(请求,请求)=>{
console.log(“在主页上”);
res.send(“主页”);
});

因为在express中,使用app.use()定义的任何内容都是中间件,它总是执行,直到或除非它定义了某个路径

app.use('/', (req, res, next)=>{
    console.log('In main page');
    res.send('<h1>Main Page</h1>');
});
app.use(“/”,(请求、恢复、下一步)=>{
console.log(“在主页上”);
res.send(“主页”);
});
上面的代码将始终执行,因为它包含根路径,并且每个url都有根路径

查看此链接以了解更多信息


您应该使用app.get(“/”)或app.post(“/”)使用express router定义路由,这将有助于获取更多信息

我可以做任何不请求faveicon.ico的事情吗?为什么
console.log('In main page')将运行,但
res.send('Main Page')不会运行?因为我的html页面输出是“产品页面”,但终端中的输出类似于我问题中的图像。正如您所知,在node.js中,所有内容都是异步的,所以两个中间件都执行了,但响应被中间件应用程序覆盖。使用('/Product',(req,res,next)=>{},因为它遵循自上而下的方法