C
C
charbet2017-08-17 16:24:47
JavaScript
charbet, 2017-08-17 16:24:47

How to put routes into separate files?

There is a file that specifies the creation of a server on express and a bunch of routes by type

app.get('/user', function(req, res) {
    if(req.isAuthenticated() && req.user.role == 'user')
        res.render('user');
});

app.post('/changeRole', function(req, res){
    console.log(req.body);
    pg.connect(connectionString, function(err, client, done){
        console.log(req);
        if(err){
            return console.error('error feetching client from pool', err);
        }
        client.query('UPDATE items SET role=($1), change=($2) WHERE name=($3)', [req.body.role, 
        	req.body.role == 'user' ? 'true' : 'false', req.body.name]);
        done();
    });
});

How can I put these routes into separate files? Or even not the routes themselves, but their handler functions.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Shashenkov, 2017-08-17
@teknik2008

Let's say we name the file handlers.js with the following content

handlers.js
module.exports.getUser = (req, res) => {
    if (req.isAuthenticated() && req.user.role == 'user')
        res.render('user');
}


module.exports.postChangeRole = (req, res) => {
    console.log(req.body);
    pg.connect(connectionString, function (err, client, done) {
        console.log(req);
        if (err) {
            return console.error('error feetching client from pool', err);
        }
        client.query('UPDATE items SET role=($1), change=($2) WHERE name=($3)', [req.body.role,
        req.body.role == 'user' ? 'true' : 'false', req.body.name]);
        done();
    });
}

And connect it to the router file
router.js
var handlers=require('./handlers');

app.get('/user', handlers.getUser);
app.post('/changeRole',handlers.postChangeRole);

A
Abcdefgk, 2017-08-17
@Abcdefgk

Take this thing

function(req, res) {
    if(req.isAuthenticated() && req.user.role == 'user')
        res.render('user');

and do this:
module.expotrts = function(req, res) {
    if(req.isAuthenticated() && req.user.role == 'user')
        res.render('user');
};

, - calling it foo.js
And then like this:
Total business

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question