从NodeJS内部调用Express Route [英] Calling Express Route internally from inside NodeJS

查看:540
本文介绍了从NodeJS内部调用Express Route的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的API有一个ExpressJS路由,我想从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);

并在我的 ./routes/api.js 文件中

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

所以如果我想从前端调用/api/update/something/:withParam的全部内容,但是我需要从NodeJS脚本的另一个方面进行调用,而不必在第二个位置重新定义整个函数

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

我曾经尝试从内部使用HTTP模块,但是我只收到"ECONNREFUSED"错误

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

我了解Express背后的想法是创建路线,但是如何在内部调用它们

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

推荐答案

处理此问题的通常"或正确"方法是让您要调用的函数本身脱离所有路由定义.也许在自己的模块中,但不一定.然后在任何需要的地方调用它.像这样:

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

这篇关于从NodeJS内部调用Express Route的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆