Home > Software engineering >  Expressjs Routes are invoked twice when running server and browsing using browser
Expressjs Routes are invoked twice when running server and browsing using browser

Time:05-29

Expressjs Routes are invoked twice when running

OS System Environment: Windows 11, ExpressJS ("express": "^4.18.1", "version": "4.18.1"), Node v16.15.0

const url = require('url');
const path = require("path");
const express = require('express');

let app = express();
console.log("instantiation");

app.use("/language", function (req, res) {
    const queryObject = url.parse(req.url, true).query;
    console.log("/ language");
    res.send("Testing server : language");
});

app.use("/", function (req, res) {
    console.log("/ path");
    res.send("Testing server : main page");
});

app.use("*", function (req, res) {
    console.log("* path");
    res.send(`"Testing my server"`);
});

app.listen(3001, "127.0.0.1", function () {
    console.log(`Server listening at `   3001);
});

Update (The following / route is still invoked twice). Anything I am missing?:

const url = require('url');
const path = require("path");
const express = require('express');

let app = express();
console.log("instantiation");

app.use("/language", function (req, res) {
    const queryObject = url.parse(req.url, true).query;
    console.log("/ language");
    res.send("Testing server : language");
});

app.use("/", function (req, res) {
    console.log("/ path");
    res.send("Testing server : main page");
});

app.listen(3001, "127.0.0.1", function () {
    console.log(`Server listening at `   3001);
});

Is it my system or a real problem with express/node?

CodePudding user response:

The reason that your route handler is invoked multiple times is because you're using app.use('/') instead of specific method handlers like app.get('/') or app.post('/').

app.use() is meant for adding middleware, and will match the base of a requested path (as opposed to using the method handlers, which will match the full path).

In other words app.use('/') will match any request that isn't already handled by other handlers declared before it. This includes requests to /favicon.ico, which a browser usually performs when opening a page. It will also match requests to /foo/bar, for instance.

More info on app.use() can be found here.

  • Related