Categories
JavaScript Answers

How to organize routes in Node.js?

Spread the love

To organize routes in Node.js, we move them to their own modules.

For instance, we write

const express = require("express");
const routes = require("./routes");
const user = require("./routes/user");
const http = require("http");
const path = require("path");

const app = express();

app.set("port", process.env.PORT || 3000);

app.get("/", routes.index);
app.get("/users/:id", user.getUser);

http.createServer(app).listen(app.get("port"), () => {
  console.log("Express server listening on port " + app.get("port"));
});

in app.js to add the routes from the other files into the app.

In routes/index.js, we write

exports.index = (req, res) => {
  res.render("index", { title: "Express" });
};

to export the index route.

And we add the getUser route into routes/user.js with

exports.getUser = (req, res) => {
  //...
};

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.