diff --git a/lib/core/util.js b/lib/core/util.js index c8e446de2d8..eda0d03c30d 100644 --- a/lib/core/util.js +++ b/lib/core/util.js @@ -102,13 +102,24 @@ function isBlobLike (object) { } } +/** + * @param {string} url The path to check for query strings or fragments. + * @returns {boolean} Returns true if the path contains a query string or fragment. + */ +function pathHasQueryOrFragment (url) { + return ( + url.includes('?') || + url.includes('#') + ) +} + /** * @param {string} url The URL to add the query params to * @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string * @returns {string} The URL with the query params added */ function serializePathWithQuery (url, queryParams) { - if (url.includes('?') || url.includes('#')) { + if (pathHasQueryOrFragment(url)) { throw new Error('Query params cannot be passed when url already contains "?" or "#".') } @@ -924,6 +935,7 @@ module.exports = { assertRequestHandler, getSocketInfo, isFormDataLike, + pathHasQueryOrFragment, serializePathWithQuery, addAbortListener, isValidHTTPToken, diff --git a/lib/util/cache.js b/lib/util/cache.js index 3c2eb0dbd29..a05530f783b 100644 --- a/lib/util/cache.js +++ b/lib/util/cache.js @@ -1,7 +1,8 @@ 'use strict' const { - safeHTTPMethods + safeHTTPMethods, + pathHasQueryOrFragment } = require('../core/util') const { serializePathWithQuery } = require('../core/util') @@ -14,12 +15,10 @@ function makeCacheKey (opts) { throw new Error('opts.origin is undefined') } - let fullPath - try { - fullPath = serializePathWithQuery(opts.path || '/', opts.query) - } catch (error) { - // If fails (path already has query params), use as-is - fullPath = opts.path || '/' + let fullPath = opts.path || '/' + + if (opts.query && !pathHasQueryOrFragment(opts.path)) { + fullPath = serializePathWithQuery(fullPath, opts.query) } return {