【问题标题】:Calling Express Route internally from inside NodeJS从 NodeJS 内部调用 Express Route
【发布时间】:2016-08-14 21:52:49
【问题描述】:

我的 API 有一个 ExpressJS 路由,我想从 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 脚本的另一个方面调用它,而不必在第二个位置再次重新定义整个函数

我尝试从内部使用 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);
});

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

【问题讨论】:

标签: javascript node.js http express routing


【解决方案1】:

处理此问题的“通常”或“正确”方法是让您要调用的函数自行分解,与任何路由定义分离。也许在它自己的模块中,但不一定。然后在需要的地方调用它。像这样:

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

【讨论】:

  • 是的,在进行了更多挖掘之后,我有点意识到这可能是唯一的方法。我不确定 Express 是否有内置的“调用你自己的路线”类型的功能。谢谢
  • 有同样的问题.. 有点明显,但不知何故我没有想到这一点。谢谢!!
  • 如果不需要调用后续中间件,这样就可以了
【解决方案2】:

这是在 Express 4 中进行内部重定向的简单方法:

魔法能做的函数是:app._router.handle()

测试:我们向 home "/" 发出请求并将其重定向到 otherPath “/其他/路径”

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)

【讨论】:

  • 我收到TypeError: Cannot read property 'handle' of undefined
【解决方案3】:

我为此制作了一个专用的中间件:uest

req 中可用,它允许您req.uest 另一条路线(来自给定路线)。

它将原始 cookie 转发给后续请求,并使 req.session 在请求之间保持同步,例如:

app.post('/login', async (req, res, next) => {
  const {username, password} = req.body

  const {body: session} = await req.uest({
    method: 'POST',
    url: '/api/sessions',
    body: {username, password}
  }).catch(next)

  console.log(`Welcome back ${session.user.firstname}!`

  res.redirect('/profile')
})

支持 Promise、await 和 error-first 回调。

更多详情请查看README

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2018-01-16
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多