你可以在快速申请之外使用express.Router吗?

时间:2016-09-04 02:53:11

标签: node.js express server router

另一种询问方式是:你能使用一个普通的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);

路由器似乎没有一个'入口点'来连接它与基本的http服务器,Express.js文档中没有任何地方使用快递应用程序之外的路由器解决,我解释the comment to this SO question意味着路由器实际上无法在没有快速框架的情况下使用,因为它缺少.listen()方法。

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

1 个答案:

答案 0 :(得分:0)

您可以将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应用程序对象的路由器。我有点工作,但有问题,因为传递给req的{​​{1}}和res对象不是router和{的预期增强版Express版本{1}}(由Express添加额外的方法)。这似乎可能会带来麻烦。为了安全地解决这个问题,您必须进行逆向工程,然后复制一堆Express app对象代码。既然我没有理由在你只能使用现有的req对象并让它做到这一点的情况下实际复制所有这些,我认为这样做是最好的。并且,Express或Express路由器的使用完全在您自己的API模块的内部,对于外部世界是不可见的,因此使用现有代码无害。