How do I use external routes in my routes index file - javascript

I have a users.js and a index.js file.
users.js
const express = require('express');
const router = express.Router();
const {catchErrors} = require('../handlers/errorHandlers');
const authController = require('../controllers/authController');
router.post('login/', catchErrors(authController.login));
module.exports.router = router;
index.js
// Route handlers
let userRouter = require('./users');
router.use('/user', userRouter);
module.exports = router;
I tried this and it's not working. I would appreciate any advice.

In your users.js file you're exporting an object with the property router (module.exports.router = router) which would look like..
module.exports = {
router: router
}
and in your index you're importing the object from users.js but not accessing the router when passing it to router.use(...).
You should pass the router in your index.js file
index.js
const express = require('express');
const router = express.Router();
// You can access the router on the require
const userRouter = require('./users').router;
router.use('/user', userRouter);
// Or on the object after the require
const userRouter = require('./users');
router.use('/user', userRouter.router);

Related

Node.js Error: Cannot GET/ from running on the web browser

So here I have 2 route files and 1 controllers for each.
My first router that is root, is working fine !
but my second route that is /teacher is giving me this error "Cannot GET /teacher"
I literally copy pasted the root route code and changed the variable names still its not working.
following are my files:
server.js
const express = require('express');
const dotenv = require('dotenv');
const root_rt = require('./routes/root-rt');
const teacher_rt = require('./routes/teacherlogin-rt')
dotenv.config();
const uri = process.env.DB_URI;
const port = process.env.PORT;
const app = express();
app.use(express.json());
app.get('/', root_rt);
app.get('/teacher', teacher_rt);
app.listen(port, () =>{
console.log(`server started on http://localhost:${port}`);
});
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.route('/')
.get(teacherController.login);
module.exports = router;
teacher-cnt
module.exports.login = function (req, res) {
res.send('this is teacher login page');
};
Thank you in advance.
When using routers, you shouldn't use app.METHOD() to mount them, but app.use():
app.use('/', root_rt);
app.use('/teacher', teacher_rt);
Make the below change in your teacherlogin-rt.js, it will start working
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.get('/', teacherController.login);
module.exports = router;
server.js
app.use('/', root_rt);
app.use('/teacher', teacher_rt);

How to combine route path if file in sub directory express

Here is my folder structure
Project
server.js
routes
auth
login.js
register.js
index.js
now my server.js look like this
const express = require("express");
const app = express();
const registerRoutes = require("./routes/auth/register");
const registerAdminRoutes = require("./routes/auth/registerAdmin");
const loginRoutes = require("./routes/auth/login");
app.use("/api-frontend", registerRoutes);
app.use("/api-backOffice", verify.isAdmin, registerAdminRoutes);
app.use("/api-backOffice/auth", loginRoutes);
As you seee i think it pretty dirty code If I've many route in future.
I want to required all path into index.js then I want to use something like in my server.js
app.use('/api', required(./routes))
Here is what I try to do
In routes/index.js I require all route
require("./auth/register");
require("./auth/login");
I'm not sure. Is their something like require 1 times and get all file in folder for make It more clean.
well after try to do something like this the error keep say in server.js
Router.use() requires a middleware function but got a Object
Here is my example register.js
const express = require("express");
const registerController = require("../../controllers/register");
const router = express.Router();
router.post(
"/register-with-social",
registerController.validate("createUser"),
registerController.registerWithSocial
);
module.exports = router;
How can I combine my routes folder In to 1 line in server.js file
You can do something like this:
routes / auth / register.js
router object will be come from server.js file and you can use here, and list your all routes here for this module.
const registerController = require("../../controllers/register");
module.exports = (router) => {
router.post(
"/api-frontend/register-with-social",
registerController.validate("createUser"),
registerController.registerWithSocial
);
// you can add more routes below if you want
}
routes / index.js
Load your all module'a route files here and export it.
module.exports = [
// AUTH REGISTER : ROUTES URL
require('./auth/register'),
// AUTH LOGIN : ROUTES URL
require('./auth/login'),
// List all your routes of auth module
];
server.js
You can initialize all your routes from index.js file, load it and use it.
const express = require("express");
const app = express();
const router = express.Router();
// just created a function,
// if you want to use direct code then you can
// if you want to store this function in any helper library then you can
async function bootstrap(uri, modules){
const index = require(uri);
for (let init of index) { await init(modules); }
}
bootstrap("./routes/index", router);
app.use('/api', router);

404 Cannot POST Using Express

I´m trying to create an API Rest in NodeJs with Express.
I have my index.js with the following code:
const express = require('express');
const routesV1 = require('./routes/v1/index');
const app = express();
routesV1(app);
app.listen(4000, () => {
console.log('Running on port: 4000');
});
then i have a routes folder with another "index.js" and a "usersRoutes".
Here´s the code of the userRoutes:
const express = require('express');
const userController = require('../../controllers/v1/UserController');
const router = express.Router();
router.post('/create', userController.createUser);
router.post('/update', userController.updateUser);
router.post('/delete', userController.deleteUser);
router.get('/get-all', userController.getUsers);
module.exports = router;
and the code of the index.js into the routes folder:
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('api/v1/users', userRoutes);
};
but when i´m consuming via Postman, with the following url: http://localhost:4000/api/v1/users/create I´m receiving a 404 error code.
Can anybody help me? thanks
I resolved it adding '/' to the route in routes/index.js
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/products', productRoutes);
};

Node.js: Centralize multiple routes into one route file

I am trying to centralize all of my route file into a index file and place that index route file in my main app file. I am trying to follow this thread
I have added app.js file. And the routes/ folder below:
When i am trying to get any of the url as mentioned below, it's showing the 404 error.
app.js:
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
routes file:
-- index.js
-- author.js
-- book.js
index.js:
const express = require('express');
const router = express.Router();
// Get Home Page of The Web Application
router.get('/', function(req, res) {
res.send('Library Home Page');
});
router.use('/author', require('./author').router);
router.use('/book', require('./book').router);
module.exports = router;
author.js:
const express = require('express');
const router = express.Router();
var AuthorController = require('../controllers/authorController');
router.get('/', AuthorController.authorList);
router.get('/:id', AuthorController.authorDetail);
router.get('/create', AuthorController.authorCreateForm);
module.exports = router;
book.js:
const express = require('express');
const router = express.Router();
var BookController = require('../controllers/bookController');
router.get('/', BookController.bookList);
router.get('/:id', BookController.bookDetail);
router.get('/create', BookController.bookCreateForm);
module.exports = router;
I want to access the url as follows:
Home:
/
Author:
/author/
/author/1
/author/create
Book:
/book/
/book/1
/book/create
module.exports = router is a default export so require('./author').router refers to an undefined property on the router, it should be:
router.use('/author', require('./author'));
And in your server entry:
app.use(indexRouter); // No `'/'` as first param

Exclude default routes form index.js file in Express.js app

I have an Express app where structure goes like this
server/
|---/model
|---/routes
|---/controllers
|---index.js
In my index.js file I'm handling default route for item
//index.js
const item = require('./routes/item');
const app = express();
// Endpoint for all operations related with /item
app.use('/item', item);
In routes directory I have a file item.js
//item.js
const express = require('express');
const router = express.Router();
const {
deleteItemById,
itemCreate,
getItemById,
updateItem
} = require('../controllers/item');
// Add new product
router.post('/create', itemCreate);
// Get product by id
router.get('/:id', getItemById);
// Delete product by id
router.delete('/:id/delete', deleteItemById);
// Update product by id
router.patch('/:id/update', updateItem);
module.exports = router;
The question is, how can I exclude line app.use('/item', item); to handle this route completely in routes/item.js file?
To have something like this in item.js file:
router.use('/item')
router.post('foo bar')
router.get('foo bar);
and in my index only require('./routes/item.js)
I don’t think you can do exactly what you want but you might be able to get close by exporting a function from item.js:
// item.js
const express = require('express')
const router = express.Router()
...
module.exports = (app) => app.use('/item', router)
...and then passing app to it in index.js:
// index.js
const express = require('express')
const app = express()
require('./routes/item')(app)
I hope this helps.
This is the approach I use for handling routes within modules:
// Init Express
const express = require ( 'express' );
const app = express ();
// Create a router (I use this approach to create multiple routers)
const apiRouter = express.Router ({});
// Include the routes module
require ( './api/v1.0/routes/item' ) ( apiRouter );
// ./api/v1.0/routes/item
module.exports = router => {
const itemController = require ( '../controllers/test' );
// Define routes here
router.post ( '/items', [
itemController.doPost
] );
router.get ( '/item/:id', [
itemController.getItem
] );
};
I create a separate router object this way so that I can create multiple routers if needed.. (one for UI app, one for API etc).
Hope this helps..

Categories