简体   繁体   中英

How to prevent express from executing subsequent routes?

I've been learning express routing and built a test server to test some express routes while also learning express-handlebars.

I have the following Routes in my Application:

    app.get("/products/search", (req, res)=>{
    console.log("Request received");
    res.render("productshome", {layout: "productsprimary"}); 
    });

    app.use((req, res)=>{
    console.log("This page does not exist");
    res.render("producterror", {layout: "productsprimary"}); 

    });

    app.listen(port, ()=>{
      console.log("Server Started"); 
    });
    

When my Server gets a get request for /products/search URL, the required handlebars (.hbs) file is sent to the Browser. However, my next Route ie app.use() gets executed as well. I don't get any errors but the flow of control goes to this Route. How do I stop this request from going to the app.use(). I'm using this Route for unrecognized URLs like /products/dsdfsdfsdfdsd and so on. Please could somebody advise what I'm doing wrong.

When you access a webpage for the first time (or when you start a new session), modern web browsers automatically send a GET request for favicon.

In your code, as the second middleware, you use an Application level middleware, where there's no mount path (so root is used). This middleware is executed for each client request if there's no handler function prior to it. In your case, "products/search" is handled by the first middleware. But then for the second request (favicon), Express skips the first middleware(because the mount path doesn't match) and executes the second middleware(as there's no mount path in it).

However this doesn't harm your app so you can just ignore it. If you want to get rid of this behaviour, use Express's serve-favicon module to send a favicon.ico to the client.

import express from 'express'
import favicon from 'serve-favicon'
const app = express()
app.get("/products/search", (req, res)=>{
console.log("Request received");
res.render("productshome", {layout: "productsprimary"}); 
});

//Midldleware to handle favicon request
app.use(favicon('favicon.ico')) //add a favicon.ico to the current path

app.use((req, res)=>{
console.log("This page does not exist");
res.render("producterror", {layout: "productsprimary"}); 

});

app.listen(port, ()=>{
  console.log("Server Started"); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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