简体   繁体   中英

Including seperate route files in node.js

I am developing an application and I have defined my custom routes in a different way. I am using Web Storm IDE to develop and it has a specific folder of routes where all the routes are kept individually. I have the following code in my directory /routes/about.js file:

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

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('about', { title: 'About Us' });
});

module.exports = router;

Now in the app.js I have written the following code to include these route and use it:

var index = require('./routes/index');
var users = require('./routes/users');
var about = require('./routes/about');

app.use('/', index);
app.use('/users', users);
app.use('/about', about);

But when I click on about link, it does not open the page. Though, if I write the route in the app.js file directly as:

app.get('/about', function (req, res) {
    res.render('about');
});

then it renders the page. Also, if I do not make separate routes and use the default routes file (/routes/index.js) and include this in that file, then also the code works fine. Can anyone explain or tell is there any mapping of these route files done which is missed by me, or I am doing something syntactically wrong

You probably created a route for /about/about . To fix, change the about router from this:

router.get('/about', ...);

to this:

router.get('/', ...);

This, then goes with:

app.use('/about', router);

which already includes the /about path. Everything in that router will already have /about at the beginning of the path.

Use below code in about file

app.get('/', function (req, res) {
    res.render('about');
});

You have already defined '/about' route in main file so if you want to render page on '/about' so you need to define route like this '/' in about page.

For example route '/about/us' then function will be in about page :

app.get('/us', function (req, res) {
    res.render('about us');
});

The method to redirect the route is correct, but you have not pass the route to app.

so you just need to do is ,

router.use('/about', about);

app.use('/', router);

Like wise add router in app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM