Express Router() method - only /api route is working while others are not

30 views Asked by At

I am getting a generic error "An error occurred during a connection to 127.0.0.1." When I try to connect to anything other than /api (/api/genres for example). My code looks like this:

index.js

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

require("./startup/cors")(app);
require("./startup/routes")(app);

const PORT = process.env.PORT || 80;
const server = app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}...`);
});

/startup/routes.js

const express = require("express");
const genres = require("../routes/genres");
const home = require("../routes/home");

module.exports = function (app) {
  app.use(express.json());

  app.use("/api", home);
  app.use("/api/genres", genres);
};

/routes/home.js

const express = require("express");
const router = express.Router();

router.get("/", (request, response) => {
  return response.send("API HOME");
});

module.exports = router;

/routes/genres.js

const express = require("express");
const router = express.Router();

router.get("/", (request, response) => {
  return response.status(200).send("success!");
});

module.exports = router;

When I navigate to http://127.0.0.1:80/api/genres, it loads forever.

I have created an entirely new project with only the four files mentioned (plus node_modules, package-lock.json, and package.json), but I still get the same issue.

2

There are 2 answers

0
Alexander Santos On

This occurs due to Express' router precedence order. Check this answer for more info about this.

TL;DR: First route is the one that is evaluated by Express.

So your code makes express go into app.use("/api", home);, as it contains /api and takes precedence.

One way to solve this is to use app.use pointing to genres' path, i.e.:

// /routes/home.js
const express = require("express");
const router = express.Router();

const genresRouter = require("./genres")

router.use("/genres", genresRouter)

router.get("/", (request, response) => {
  return response.send("API HOME");
});

module.exports = router;

This will make all routes from genresRouter accessible by /api/genres/*

0
Autumn V On

SOLUTION: - In my actual project inside /routes/home.js, I was trying to handle unknown endpoints by having a /api/:endpoint route.

The router couldn't tell whether to handle unknown endpoints using /api/:endpoint in /routes/home.js or app.use("/api/genres", genres) in index.js. Poor design was the source of my error (NOT any syntax errors).

Thank you for taking time out of your day to help me troubleshoot my issue!