Fri*_*esh 17 javascript routing http node.js express
我的API有一个ExpressJS路由,我想从NodeJS中调用它
var api = require('./routes/api')
app.use('/api', api);
Run Code Online (Sandbox Code Playgroud)
在我的./routes/api.js文件中
var express = require('express');
var router = express.Router();
router.use('/update', require('./update'));
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
所以,如果我想/api/update/something/:withParam从我的前端调用它的全部查找,但我需要在我的NodeJS脚本的另一个方面调用它,而不必在第二个位置再次重新定义整个函数
我试过从里面使用HTTP模块,但我只是得到一个"ECONNREFUSED"错误
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);
});
Run Code Online (Sandbox Code Playgroud)
我理解Express背后的想法是创建路由,但我如何在内部调用它们
bch*_*iej 19
处理此问题的"通常"或"正确"方法是让您要调用的函数自行分解,与任何路径定义分离.也许在自己的模块中,但不一定.然后只需在任何需要的地方调用它.像这样:
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(...);
// ..
}
Run Code Online (Sandbox Code Playgroud)
这是在Express 4 中进行内部重定向的一种简单方法:
魔术可以做的功能是:app._router.handle()
测试:我们向home "/"发出请求并将其重定向到otherPath "/other/path"
var app = express()
function otherPath(req, res, next) {
return res.send('ok')
}
function home(req, res, next) {
req.url = '/other/path'
/* Uncomment the next line if you want to change the method */
// req.method = 'POST'
return app._router.handle(req, res, next)
}
app.get('/other/path', otherPath)
app.get('/', home)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14268 次 |
| 最近记录: |