Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

javascript - Calling Express Route internally from inside NodeJS

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

and inside my ./routes/api.js file

var express = require('express');
var router = express.Router();
router.use('/update', require('./update'));  
module.exports = router;

so if I want to call /api/update/something/:withParam from my front end its all find, but I need to call this from within another aspect of my NodeJS script without having to redefine the whole function again in 2nd location

I have tried using the HTTP module from inside but I just get a "ECONNREFUSED" error

http.get('/api/update/something/:withParam', function(res) {
   console.log("Got response: " + res.statusCode);
   res.resume();
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

I understand the idea behind Express is to create routes, but how do I internally call them

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(...);
    // ..
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...