Skip to content

Commit

Permalink
fix: auto reply to OPTIONS requests only when unhandled (#4559)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
alan-agius4 authored Sep 7, 2022
1 parent 85dcb31 commit 984af02
Showing 1 changed file with 22 additions and 26 deletions.
48 changes: 22 additions & 26 deletions lib/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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);
}
Expand Down

0 comments on commit 984af02

Please sign in to comment.