从 NodeJS 内部调用 Express Route [英] Calling Express Route internally from inside NodeJS
问题描述
我的 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屋!