Calling Express Route internally from inside NodeJS

前端 未结 3 1448
忘了有多久
忘了有多久 2020-12-06 04:18

I have an ExpressJS routing for my API and I want to call it from within NodeJS

var api = require(\'./routes/api\')
app.use(\'/api\', api);

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 04:43

    The 'usual' or 'correct' way to handle this would be to have the function you want to call broken out by itself, detached from any route definitions. Perhaps in its own module, but not necessarily. Then just call it wherever you need it. Like so:

    function updateSomething(thing) {
        return myDb.save(thing);
    }
    
    // elsewhere:
    router.put('/api/update/something/:withParam', function(req, res) {
        updateSomething(req.params.withParam)
        .then(function() { res.send(200, 'ok'); });
    });
    
    // another place:
    function someOtherFunction() {
        // other code...
        updateSomething(...);
        // ..
    }
    

提交回复
热议问题