Nodejs Express router.get('/') in users.js - node.js

I m still trying to learn NodeJs but I came across this path thing I encountered in Express. When I create an app using Express I noticed that in app.js I have these lines of code var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
And in users.js I already have configured
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
I don t really understand why is it in users.js router.get('/') instead of router.get('/users') as it is specified in app.js? Can someone explain a bit what s going on in this case?
As far as I understand in app.js it says whenever someone tries to access the specified route('/users') lets say localhost:3000/users in the browser, let the file required in users variable handle it.

If you are working with routes the express app is automatically . Here is an example from the express.js website:
In our router file we have:
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Then in our main file were we have our server etc we load in the router:
var birds = require('./birds')
// ...
app.use('/birds', birds)
These routes in the router app are only accessed when there is a request to to /birds url. All the routes in the router are now automatically staring with /birds
So this code in the express router:
// im code in the birds router
router.get('/about', function (req, res) {
res.send('About birds')
})
Is only executed when someone makes a get request to the /birds/about url.
More information in the official express.js docs

I would just like to point out what I have learnt today after some frustration, and maybe somebody can elaborate as to why this happens. Anyway, if, like me, you want to use '/users' for all user routes or '/admin' for all administrator routes then, as WillemvanderVeen mentioned above, you need to add the following code to your main app.js file
var users = require('./routes/users')
app.use('/users', users)
However, one thing which was not mentioned is that the order with which you declare your 'app.use('/users', users)' in app.js is important. For example, you would have two route handling files as so:
/routes/index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => { res.render('index') });
/routes/users.js
const express = require('express'); const router = express.Router();
router.get('/', (req, res) => { res.send('users route') })
You would then require them in your main app.js file as so:
app.js
const express = require('express');
const app = express();
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
and you would expect that when you hit the '/users' route that you would receive the res.send('users route') page.
This did not work for me, and I struggled to find any solution until recently, which is why I am now commenting to help you.
Instead, I swapped the app.use() declarations in app.js around like so and it worked:
app.js
const express = require('express');
const app = express();
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/users', users);
app.use('/', index);
Now when I hit '/users' I see the 'users route' message. Hope this helped.
To answer your question though, when you configure the route handler in app.js as users, then you are requiring a router file (./routes/users) to handle all requests from that file and sending them to the URL /users first. So if you do the following:
/routes/users.js
router.get('/dashboard', (req, res) => {
// get user data based on id and render it
res.render('dashboard')
});
then whenever user is logged in and goes to dashboard, the URL will be /users/dashboard.

Related

How do I split up my routes using Express.Router() into multiple files?

I am trying to figure out how to split the routes in my routes.js file into multiple files. My current routes.js file looks like this:
const pullController = require('./controllers/pullController');
const userController = require('./controllers/userController');
const routes = require('express').Router();
routes.get('/openpullinfo', pullController.getOpenPullRequestInfo);
.
.
.
routes.post('/user', userController.createUser);
module.exports = routes;
I want to have a different routes file (i.e. userRoutes.js) for each controller because there are just too many routes in my single routes.js file and it's becoming unmanageable.
You can create a set of routes file (userRoutes.js, pullRoutes.js...). In these files, you can use the express.Router class to create modular, mountable route handlers. Then in the main file, you mount all your routers in your Express application.
Example :
userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Get users controller');
});
router.post('/', function (req, res) {
res.send('Post user controller');
});
module.exports = router;
server.js
const express = require("express");
const app = express();
app.use(express.urlencoded())
app.use(express.json())
const userRoutes = require('./userRoutes');
app.use('/users', userRoutes);
app.listen(80);
In the browser, http://localhost/users gives me the text Get users controller

Why express.Router() while separating routes

I have gone through express document in that i have learn about
Router() and express.Router(). so my question is i have separated
my all routes from main app and created different folder there i did
not create any router object(var router express.Router()) for
routing to specific path still it's working fine. So i want to know
why this Router class is necessary ?
see, This is main app file,
'use strict'; const startUpDebugger=require('debug')('app:startUp');
const dbDebugger=require('debug')('app:db'); const express =
require('express'); const app = express(); const
moragan=require('morgan'); const helmet=require('helmet'); const
config=require('config'); const courses=require('./routes/courses');
const home=require('./routes/home'); app.use(helmet());
app.set('view engine','pug'); app.set('views','./view');
app.use(express.json()); app.use('/api/courses',courses);
app.use('/',home);
console.log(Node enironment variable: ${process.env.NODE_ENV});
console.log(Application name : ${config.get('name')});
console.log(mail server : ${config.get('mail.host')});
if(app.get('env')==='development'){
app.use(moragan('tiny'));
startUpDebugger("******Morgan enabled*******") }
const port = process.env.PORT || 5000; app.listen(port);
console.log(Api Node running on port ${port});
This is my courses.js which is my route file
const express=require('express'); const app=express
const courses=[{"id":1,"course":"course1"},
{"id":2,"course":"course2"},
{"id":3,"course":"course3"},
{"id":4,"course":"course4"}]
app.route('/posting').post((req,res)=>{
console.log(req.body);
courses.push(req.body)
res.status(201).send(courses); }).put((req,res)=>{
res.send("Successfully put message") }) app.get('/sub/:id',(req,res)=>{
res.status(200).send(req.params); })
module.exports=app;
your question is not clear but if i am getting you right:-
If your app is really simple, you don't need routers.
//you can just invoke express constructor and use it
const app=express()
app.get('/', function (req, res) {
res.send('root')
}) // app.get,app.post and so on
in your main app file.
But as soon as it starts growing, you'll want to separate it into smaller "mini-apps", so that it's easier to test and maintain, and to add stuff to it. You'll avoid a huge main app file :) .
so here you need to make another file for routes and have to invoke express.Router() class and use it
like:
//route.js
const Router=express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
And import this file into the main app file and pass it to middleware to use
app.use('/',require('./routes/routes.js'))
and comparing to express() object the express.Router() object is light weight

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;
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

Express router basic usage resulting in 404

I am trying to build my express app to have routes within routes as shown below and I am getting a 404 error.
What I am trying to do is simply, route all traffic with api in the route to the routes/api.js file, then from there, based on the end of the url, depending on if its signup or login, route to the corresponding signup.js or login.js file.
Note, moving the code from routes/signup.js to routes/app.js works perfectly fine.
Has anyone gotten unexpected 404 errors under a similar set up? I appreciate any suggestions on how to resolve.
server/index.js
import express from 'express';
const app = express();
app.use('/api', require('./routes/api'));
app.use('*', (req,res) => {
res.status(404).send('404: Not Found');
});
app.listen(3000, function() {
console.log('api is running on port 3000');
});
server/routes/api.js
var express = require("express");
var router = express.Router();
router.use('/signup', require('./signup'));
router.use('/login', require('./login'));
module.exports = router;
server/routes/signup.js
var express = require("express");
var router = express.Router();
router.post('/api/signup', (req, res) => {
res.send('HELLO WORLD');
});
module.exports = router;

express4 router skipping base route and going directly to a sub-route

I have an express4 router that is skipping the base route and going directly to a designated ./user route. But I can not see why it is skipping the base route.
APP.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();
require('./routes')(app);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//app.use('/', router);
module.exports = app;
./routes/index.js
var express = require('express');
var router = express.Router();
// route middleware that will happen on every request
router.use(function(req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
/* GET home page. */
router.get('/', function(req, res) {
console.log('inside the root route');
});
//module.exports = router;
module.exports = function(app) {
// here we list our individual sets of routes to use in the router
require('./route/user')(app);
};
When I run the app (npm start), console displays the log that resides inside the user route and totally skips the base route ('/').
Where did I go wrong??
It appears that you are only exporting the user routes.
To make this a bit clearer, app.js only has access to the following when you require routes.index.js:
function(app) {
// here we list our individual sets of routes to use in the router
require('./route/user')(app);
};
hence why it is skipping the base route entirely.
Following the API documentation (under the 'express.Router' section), the correct code to export the routes would be:
// exports the router.use and router.get('/) routes
module.exports = router
Which would mean you'd have to include the user routes in another section (such as app.js).

Resources