I get the following error when adding middleware:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:533:11)
at xDnsPrefetchControlMiddleware (D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\helmet\dist\middlewares\x-dns-prefetch-control\index.js:7:13)
at internalNext (D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\helmet\dist\index.js:73:13)
at HelmetMiddleware.helmet [as handler] (D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\helmet\dist\index.js:75:9)
at HelmetMiddleware.use (file:///D:/Projekte/0_Privat/Node/heimdall.js/server/src/infrastructure/express/HttpInfrastructure.ts:32:14)
at HelmetMiddleware (D:\Projekte\0_Privat\Node\heimdall.js\src\driver\express\ExpressDriver.ts:69:91)
at Layer.handle [as handle_request] (D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\express\lib\router\index.js:317:13)
at D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\Projekte\0_Privat\Node\heimdall.js\server\node_modules\express\lib\router\index.js:335:12)
This way I add the middleware:
this.app = createExpressServer({
controllers: this.controler,
cors: true,
defaultErrorHandler: false
});
this.app.use(helmet());
If I put a wrapper around the existing middleware, it works.
@Middleware({ type: "before" })
class HelmetMiddleware implements ExpressMiddlewareInterface {
private readonly handler: RequestHandler = helmet();
public use (request: any, response: any, next: (err: any) => any): void {
this.handler(request, response, next);
}
}
this.app = rc.createExpressServer({
controllers: this.controler,
middlewares: [
HelmetMiddleware
],
cors: true,
defaultErrorHandler: false
});
I can reproduce the above error if I change the type to "after" (@Middleware({ type: "after" })). So it looks like when the middleware is added via the "use" mechanism, it is always handled in "after" mode. Am I missing something or am I doing something wrong causing the error?
I'm running into this issue as well but in my situation it's a 404 handler firing after the controller had already returned a response. Don't know if there was some sort of condition I needed to use to check whether a response had already been sent.
I had the same issue. I could solve it by creating the Express instance myself and then using the 鈥渦seExpressServer()" method.
const app: Application = express();
app.use( helmet() )
useExpressServer( app, {
routePrefix: '/api',
development: false,
defaultErrorHandler: false,
validation: true
} )
Most helpful comment
I had the same issue. I could solve it by creating the Express instance myself and then using the 鈥渦seExpressServer()" method.