anthonyv
anthonyv

Reputation: 2465

Manually injecting express app via `http.createServer` proxy

I am currently authoring a component for a users sites which adds a number of resources to their server. For my part, I am wanting to use express, but the user could be using express themselves or some other web framework.

Because I want this to just work out of the box, I was attempting to setup my express pipeline via proxying http.createServer. Injecting the pipeline this way seems to work reasonably well in cases where I handle the request, but it fails in cases where I let it fall through and execute the users callback (specifically, it says that the response headers have been sent already).

Here is the sample I am working on. Any ideas?

var http = require('http');
var express = require('express');

var setupProxy = function setupProxy() {
    var app = buildApp();

    var oldCreateServer = http.createServer;
    http.createServer = function(callback) { 
        return oldCreateServer(function(req, res) {n
            app.apply(this, arguments);

            if (!res.finished) {
                callback.apply(this, arguments);
            }
        });
    };
};

var buildApp = function buildApp() {
    var app = express();

    app.use('/test', function(req, res) {
        res.send('Hello World');
    });

    return app;
};

Upvotes: 0

Views: 86

Answers (1)

jfriend00
jfriend00

Reputation: 707396

I suspect your express handling creates a default 404 response when it doesn't match any of your routes. So, that would be the cause of the headers already sent issue when you are not handling it, but trying to pass it on.

So, I think you need your own 404 handler that writes nothing to the request (e.g. does nothing), but keeps Express from handling it.

Or, another possibility would be to call the user's server callback from your express 404 handler and not elsewhere.

Upvotes: 1

Related Questions