Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to app use all routes from different file

I'm trying to separate my routes, previously i'm including them to my app.js

/backend/app.js

const express = require("express");
const router = require("./routes");
const status = require("./routes/status");
const register = require("./routes/register");
const login = require("./routes/login");


app.use('/', router);
app.use('/status', status);
app.use('/login', login);
app.use('/register', register);

I realized its not ideal since i am adding more and more routes later on and the app.js will be polluted with them

What i want to do now is just to import an index.js to app.js and basically this index have all the routes needed

/backend/routes/index

const routes = require("express").Router();
const root = require("./root");
const status = require("./status");
const register = require("./account/register");
const login = require("./account/login");


routes.use("/",  root);
routes.use("/login", login);
routes.use("/register", register);
routes.use("/status", status);
and now in the app.js i can just include the index

const routes = require("./routes");
app.use('/', routes);

but its not working im getting 404 error when trying to request to login route

im exporting them like this

module.exports = routes;

like image 465
Jacobs Naskzmana Avatar asked Nov 30 '25 10:11

Jacobs Naskzmana


1 Answers

In your app.js

app.use('/', require('./backend/routes/index'))

Then, in your routes/index

import express from 'express'

const router = express.Router()

// GET /
router.get('/', function (req, res) {

})

// GET /countries
router.get('/countries', (req, res, next) => {

})

// POST /subscribe
router.post('/subscribe', checkAuth, generalBodyValidation, (req, res, next) => {

})

// All routes to /admin are being solved in the backend/routes/admin/index file
router.use('/admin', require('./backend/routes/admin/index'))

module.exports = router

Your admin/index file can be import express from 'express'

const router = express.Router()

// POST /admin/login
router.post('/login', (req, res, next) => {

})

module.exports = router

With this, you will be able to perform a POST request to /admin/login.

Hope this solves your problem, if it does mark my answer as correct, if not tell me what went wrong and I will solve it :D

like image 75
Pedro Silva Avatar answered Dec 01 '25 23:12

Pedro Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!