簡體   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