From cb813e4292a8fff7fe1999a38258baa6bf18f7d0 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 6 Sep 2022 07:57:14 +0000 Subject: [PATCH] fix: auto reply to OPTIONS requests only when unhandled Prior to this change the internal options middleware always responsed to such requests. This is because the middleware was registered too early and was not being used as a fallback. With this change we register this middleware as the last middleware to ensure that this is only used as a fallback when OPTIONS requests are not handled. Closes #4551 --- lib/Server.js | 48 ++++++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 057d5ad40b..6f2116943e 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -2131,32 +2131,6 @@ class Server { }); } - { - /** - * - * @param {Request} req - * @param {Response} res - * @param {NextFunction} next - * @returns {void} - * - */ - const optionsRequestResponseMiddleware = (req, res, next) => { - if (req.method === "OPTIONS") { - res.statusCode = 204; - res.setHeader("Content-Length", "0"); - res.end(); - return; - } - next(); - }; - - middlewares.push({ - name: "options-middleware", - path: "*", - middleware: optionsRequestResponseMiddleware, - }); - } - middlewares.push({ name: "webpack-dev-middleware", middleware: @@ -2411,6 +2385,28 @@ class Server { }); } + // Register this middleware always as the last one so that it's only used as a + // fallback when no other middleware responses. + middlewares.push({ + name: "options-middleware", + path: "*", + /** + * @param {Request} req + * @param {Response} res + * @param {NextFunction} next + * @returns {void} + */ + middleware: (req, res, next) => { + if (req.method === "OPTIONS") { + res.statusCode = 204; + res.setHeader("Content-Length", "0"); + res.end(); + return; + } + next(); + }, + }); + if (typeof this.options.setupMiddlewares === "function") { middlewares = this.options.setupMiddlewares(middlewares, this); }