MEAN STACK Routing - doing order - node.js

I am a MEAN stack beginner and i cannot find a solution for my routing problem.
I would like to divide all routes from the app.js file, so i create a file which contains all routes of my application.
I get a NOT FOUND issue or an infinite cycle request.
This is what i have in my app.js
app.use(require('./routes/config'));
And here what there is in the routes/config
var express = require('express');
var router = express.Router();
router.get('/partials/:name', require('./partials'));
router.get('/api/tickets', require('./api/tickets'));
router.get('/tickets', require('./tickets'));
router.get('/', require('./index'));
module.exports = router;
and in one route i have:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
Could you please help me and tell me what is wrong and why?
Thanks in advance.

in your config file you need to use the router like this:
router.use('/partials/:name', require('./partials'));
and for the partials will be a route, in your partials file omit the next attribute;
router.get('/', function(req, res) {
res.render('index');
});

Related

Nodejs Express router.get('/') in users.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.

Express routing on root "/" doesn't work in app.get

I've been having this issue where for some reason the Express route doesn't see my root get function. I've declared my app.js this way:
var index = require('./app/routes/index');
var app = express();
app.use('/', index);
Then in my index.js I have my definition this way:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
console.log('Enter root.');
});
router.get('/something', function(req, res, next) {
console.log('Enter something.');
});
Express routes into '/something' just fine, but couldn't see '/'. Anybody have an idea why it doesn't work? Thanks.
Modified based on new info:
If you're getting a 304 status back in the browser, that's because the browser has cached the GET request and the server is telling the browser that the page has not been changed so the browser can just use the cached copy.
You can make the page uncacheable by changing the headers the server sends with the request.
See Cache Control for Dynamic Data Express.JS and NodeJS/express: Cache and 304 status code and Nodejs Express framework caching for more info.
You show no exports in index.js so this line:
var index = require('./app/routes/index');
does not accomplish anything. index is an empty object and thus this:
app.use('/', index);
doesn't do anything and, in fact, may even cause an error.
Perhaps what you want is this:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
console.log('Enter root.');
});
router.get('/something', function(req, res, next) {
console.log('Enter something.');
});
// export your router
module.exports = router;
Then, index in your other file will be the router.

Combine routes from multiple files in ExpressJS?

What is the best way to combine routes from two files so Express Router will handle them at the same level? I'm thinking of something like this:
Default Routes File
This file would be generated and overwritten every time the generator runs:
var express = require('express'),
router = express.Router(),
custom = require('./custom.routes');
router.get('/', function (req, res) {
});
router.post('/', function (req, res) {
});
router.put('/', function (req, res) {
});
router.use('/', custom);
module.exports = router;
Custom Routes File
This file would only be generated the first time and would never be overwritten.
var express = require('express'),
router = express.Router();
router.post('/custom-method', function (req, res) {
});
module.exports = router;
Parent Route File
This file is generated and overwritten constantly. It is responsible for providing the top level api route:
var express = require('express'),
apiRouter = express.Router();
var widgetRouter = require('./widget.routes');
apiRouter.use('/widgets', widgetRouter);
var sprocketRouter = require('./sprocket.routes');
apiRouter.use('/sprockets', sprocketRouter);
module.exports = apiRouter;
The obvious goal is to allow the developer to customize the routes and know his work will be safe even when the generator is run again.
router.use() does not necessarily need to take you deeper in the tree. You could just add the following line before the exports of the first file.
router.use('/', require('./routes.custom.js'));
With this you can also remove the wrapper from the custom file.

Node.js - external middleware causing 404

I have a simple express app (version 4.9.0) and I am trying to put my middleware in to external files.
My app.js has:
var middleware = require('./lib/middleware');
app.get('/foo', middleware.configcache);
/lib/middleware contains index.js:
exports.configcache = require('./configcache.js');
/lib/middleware/configcache.js contains:
function configcache(req, res, next) {
console.log("hello world");
next();
}
module.exports = configcache;
When I make a GET request to /foo I get a 404. Can anyone advise?
This is how I use it in one of my apps:
app.js:
var routes = require('./routes/index');
routes/index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', {
title: req.i18n.t("meta.title.index")
});
});
module.exports = router;
I scaffolded this express project with the yeoman express generator: yo express
So the answer to your problem is: Don't call next(), but send an actual response to the browser - when you are using router.get():
function configcache(req, res, next) {
res.send(200, 'hello world');
}
or use router.use like described here: http://expressjs.com/guide/using-middleware.html

What is the difference between "express.Router" and routing using "app.get"?

I have an app with following code for routing:
var router = express.Router();
router.post('/routepath', function(req, res) {});
Now I have to put routing code in different files so I tried to use this approach, but it is not working perhaps because instead of express.Router() it uses:
app.post("/routepath", function (req, res) {});
How can I put routing in different files using express.Router()?
Why app.get, app.post, app.delete, etc, are not working in app.js after using express.Router() in them?
Here's a simple example:
// myroutes.js
var router = require('express').Router();
router.get('/', function(req, res) {
res.send('Hello from the custom router!');
});
module.exports = router;
// main.js
var app = require('express')();
app.use('/routepath', require('./myroutes'));
app.get('/', function(req, res) {
res.send('Hello from the root path!');
});
Here, app.use() is mounting the Router instance at /routepath, so that any routes added to the Router instance will be relative to /routepath.

Resources