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.
This occurs due to Express' router precedence order. Check this answer for more info about this.
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.:This will make all routes from
genresRouter
accessible by/api/genres/*