Node.js & Express.js: 如何重定向到另一个 router/middleware

Node.js & Express.js: How to redirect to another router/middleware

我正在使用 VENoM 堆栈开发一个应用程序,在 API 我有一些像这样的中间件:

const express = require('express');

const router = express.Router();

require('./routes/orderRoutes')(router);
require('./routes/userRoutes')(router);
require('./routes/ftpRoutes')(router);

module.exports = router;

我的每个路由器都有不同的“路径”,我的意思是,调用 API 基础 URL 是 https://localhost:8081/api/。 .. 每个路由器都以不同的路由开始,例如 /order/... /ftp/... 或 /user/...

问题是,我想像这样从 ftpRoutes 调用 GET 路由到 orderRoutes

router.get('/ftp/importFiles', async function(request, response, next) {
        client.ftp.verbose = true
        try {
            await client.access(ftpTest)
            let files = await client.list('/');
            files = files.map((file) => { return path.join(downloadsPath, file.name) });
            console.log(files);
            if (!fs.existsSync(downloadsPath)) {
                fs.mkdirSync(downloadsPath, { recursive: true });
            }
            await client.downloadToDir(downloadsPath, '/');
            console.log(files)
            request.session.files = files;
        } catch (err) {
            console.log(err)
        }
        client.close()
    })

从这个路由,也就是 http://localhost:8081/api/ftp/importFiles 我想调用到 http://localhost:8081/api/order/parseOrder。 我试过使用一些选项,例如:

但我无法使重定向正常工作,所以我想将 /ftp/importFiles 请求更改为订单路由器,但我想单独保留它。有什么解决方案可以从一个路由器重定向到另一个路由器吗?

您实际上要求做的不是重定向。重定向告诉调用客户端他们请求的 URL 没有他们想要的资源,相反,他们应该通过向不同的 URL.[=14= 发送 http 请求来请求不同的资源。 ]

那不是你想要做的。您正试图在当前路由的处理中使用来自不同路由的功能。您想要 return 当前路线的结果。有几种方法可以做到这一点。

  1. 向您自己的服务器发出 HTTP 请求。您可以从字面上向您自己的 Web 服务器发出 HTTP 请求,并使用其他路由获取响应http.request() 或更高级别的库,例如 node-fetch()got()axios().

  2. 将通用代码分解为一个新函数并在两个地方调用它。您可以从其他途径获取您想要的功能并将该功能分解为一个公共共享函数,您可以从两个想要使用该功能的路由中调用它。然后,无需向您自己的服务器发出新的 http 请求,您只需调用一个 Javascript 函数来执行您想要的处理并获得结果,您可以在任何地方使用该函数 need/want .

我几乎总是建议将公共代码分解为共享函数,因为它最终会更加灵活。