express icon indicating copy to clipboard operation
express copied to clipboard

Response built by express is broken if res and req don't extend node's http.IncomingMessage and http.ServerResponse

Open Tofandel opened this issue 1 year ago • 1 comments

To reproduce

import createApp from 'express';

const app = createApp();
console.log(app.response);

console.log(app.response.getHeader('vary'));
import createApp from 'express';
import {IncomingMessage} from 'unenv/runtime/node/http/_request'
import {ServerResponse} from 'unenv/runtime/node/http/_response'

const req = new IncomingMessage();
const res = new ServerResponse(req);

// Taken from express init middleware implementation
const app = createApp();
Object.setPrototypeOf(res, app.response);

res.setHeader('vary', 'test'); // TypeError: Cannot set properties of undefined (setting 'vary')
node:_http_outgoing:747
  const entry = headers[name.toLowerCase()];
                       ^

TypeError: Cannot read properties of undefined (reading 'vary')
    at ServerResponse.getHeader (node:_http_outgoing:747:24)

Because the non native response methods are being overwritten with the native methods

Solution:


var request = require('./request');

/**
 * Response prototype.
 * @public
 */

var res = new http.ServerResponse(request)

Tofandel avatar Oct 11 '24 14:10 Tofandel

See also https://github.com/expressjs/express/issues/2548 and https://github.com/unjs/node-mock-http/issues/5

Tofandel avatar Oct 11 '24 14:10 Tofandel