Home > Back-end >  How can I seperate different routes in different files in nodejs?
How can I seperate different routes in different files in nodejs?

Time:05-25

I'm learning reactjs and nodejs and with help of fellow stackoverflow members i've been able to successfully create the front end. Now i'm working on the back end in nodejs. Nodejs is also working fine but right now all my code is in single index.js file and i'm worried that its going to get bigger and bigger.

I just want to know how can I move stuff from index.js to seperate files ? For eg. I have catgeories (add,modify,delete list) then same for products, users etc.

My routes are like:

/add-category
/mod-category
/del-category
/categories

/add-user
/mod-user
/del-user
/users

/add-product
/mod-product
/del-product
/products

They're all working fine, just that they're in a single index.js file. How can I move routes of products into products.js and subsequently categories into categories.js and users into users.js ?

Some of my code is following as to how my index.js is:

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

app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "",
    database: "shop",
});

app.get("/admin/categories", (req, res) => {
    db.query("SELECT * FROM categories ORDER BY catg_name", (err, result) => {
        if (err) {
            console.log(err);
        } else {
            res.send(result);
        }
    });
});

app.put("/admin/mod-category", (req, res) => {
    const id = req.body.id;
    const name = req.body.name;
    const description = req.body.description;
    const status = req.body.status;

    db.query(
        "UPDATE categories SET catg_name = ?, catg_description = ?, catg_status = ? WHERE catg_id = ? LIMIT 1",
        [name, description, status, id],
        (err, result) => {
            if (err) {
                console.log(err);
            } else {
                res.send(result);
            }
        }
    );
});

app.delete("/admin/del-category/:id", (req, res) => {
    const id = req.params.id;

    db.query(
        "DELETE FROM categories WHERE id = ? LIMIT 1",
        [id],
        (err, result) => {
            if (err) {
                console.log(err);
            } else {
                res.send(result);
            }
        }
    );
});

app.listen(3001, () => {
    console.log("Server is running on port 3001");
});

Any help is appericiated.

Thanks.

CodePudding user response:

you can create a separate file for each collection.

categories routes file

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

router.get('/categories/:id', (req, res) => {
  // get a category by ID
});

router.post('/categories', () => {
  // create a category
});

module.exports = router;

then a file for the products

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

router.get('/products/:id', (req, res) => {
  // get a product by id
});

router.post('/products', () => {
  // create a product
});

module.exports = router;

after that import the exported routers to your index file and use them with app.use() function

const express = require('express');
const productsRouter = require("./src/productsRouter");
const categoriesRouter = require("./src/categoriesRouter");

const app = express();

app.use(productsRouter);
app.use(categoriesRouter);

CodePudding user response:

In this particular case, you can define each endpoint action as a file function.

You can do a categories.js file with any function that you need

const database = require('./connection.js')

const CATEGORIES = {

    edit_categories : (req, res) => {
        ...
    },

    delete_categories : (req, res) => {
        ...
    },

    find_categories : (req, res) => {
        ...
    }

}

module.exports = CATEGORIES

And apart you can define your connection.js

const mysql = require("mysql");

const database = () =>{
    const db = mysql.createConnection({
        user: "root",
        host: "localhost",
        password: "",
        database: "shop"
    });
    return db;
}

module.exports = database();

And then use it all

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

const  CATEGORIES  = require('./categories.js');

app.use(cors());
app.use(express.json());


app.get("/admin/categories", CATEGORIES.find_categories );
app.put("/admin/mod-category", CATEGORIES.edit_categories );
app.delete("/admin/del-category/:id", CATEGORIES.delete_categories );

app.listen(3001, () => {
    console.log("Server is running on port http://127.0.0.1:3001");
});

Obviously there is some many different ways for structure your project (you can separate routes, modeling and views on that way)

  • Related