繁体   English   中英

您可以在Express应用程序之外使用express.Router吗?

[英]Can you use express.Router outside of an express application?

询问的另一种方式是:可以在普通的http服务器上使用express.Router的实例吗? 例如:

const router = require('express').Router();
router.get("/", (req, res) => console.log("Routing..."));
require("http").createServer((req, res) => { /* how to use router here?*/ }).listen(3000);

Router似乎没有“入口点”将其与基本的http服务器连接,Express.js文档中的任何地方都没有在Express应用程序外部使用Router来解决它,我对此SO问题的解释指由于缺少.listen()方法,因此路由器实际上不能在没有快速框架的情况下使用。

我问是因为我正在编写一个需要API路由的节点模块,并且我希望可以将其自由地放入任何类型的服务器中。 Express只是我正在寻找的路由解决方案之一。

您可以将Express路由器连接到普通的node.js http服务器,同时仍然允许其他路由用于路由器未处理的路由。 但是,您必须创建一个Express应用并使用该对象,但是该Express对象不必接管Web服务器,它只能用于您的路由。 运作方式如下:

API用户的代码:

// generic node.js http server created by the user of your API
const http = require('http');
const server = http.createServer(function(request, response) {
    // the user of your API has to insert a handler here
    // that gives your API a first crack at handling the http request
    libRouter(request, response, function() {
        // if this callback is called, then your API did not handle the request
        // so the owner of the web server can handle it
    });
});
server.listen(80);

您的API代码:

// you create your desired Express router
const express = require('express');
const router = express.Router();

// define the handlers for your router in the usual express router fashion
router.get("/test", function(req, res) {
    res.send("Custom API handled this request");
});

// your create an Express instance 
const app = express();
// hook your router into the Express instance in the normal way
app.use("/api", router);


// define a handler function that lets the express instance
// take a crack at handling an existing http request without taking over the server
function apiHandler(req, res, done) {
    // call app.handle() to let the Express instance see the request
    return app.handle(res, res, done);
}

这样,您对Express和Express路由器的使用完全在代码内部。 您只需要一个现有的node.js http服务器来使用正确的参数调用函数apiHandler(req, res, doneFn) 仅当您的api没有处理请求时,才会调用done回调。在这种情况下,API的用户应处理该请求。

此示例为/api/test定义了一条路由,您可以根据需要定义任意数量的/api/xxx路由。 您甚至可以在app对象上使用多个路由器,每个路由器具有不同的前缀路径,它将检查所有路由器。


作为记录,我尝试仅使用没有Express应用程序对象的路由器。 我有点得到它的工作,但也有因为一些问题reqres对象传递给router并不预期增强的快速版本reqres (通过快速添加额外的方法)。 这似乎可能引起麻烦。 为了安全地解决该问题,您必须进行反向工程,然后复制一堆Express应用程序对象代码。 由于我认为没有理由在可以仅使用现有app对象并让其正常进行的情况下重复所有操作,因此我认为最好这样做。 而且,使用Express或Express路由器完全在您自己的API模块内部,外界看不见,因此使用有效的现有代码不会有任何危害。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM