diff --git a/lib/Server.js b/lib/Server.js index 87c4edb347..8dca1191b5 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -3235,15 +3235,18 @@ class Server { // For convenience, always allow localhost (hostname === 'localhost') // and its subdomains (hostname.endsWith(".localhost")). // allow hostname of listening address (hostname === this.options.host) - const isValidHostname = validateHost - ? ipaddr.IPv4.isValid(hostname) || - ipaddr.IPv6.isValid(hostname) || - hostname === "localhost" || - hostname.endsWith(".localhost") || - hostname === this.options.host - : false; - - return isValidHostname; + if ( + ipaddr.IPv4.isValid(hostname) || + ipaddr.IPv6.isValid(hostname) || + hostname === "localhost" || + hostname.endsWith(".localhost") + ) { + return true; + } + if (!validateHost) { + return false; + } + return hostname === this.options.host; } /** diff --git a/test/e2e/cross-origin-request.test.js b/test/e2e/cross-origin-request.test.js index d003024928..ed3202ce12 100644 --- a/test/e2e/cross-origin-request.test.js +++ b/test/e2e/cross-origin-request.test.js @@ -4,6 +4,7 @@ const webpack = require("webpack"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); const runBrowser = require("../helpers/run-browser"); +const { startServer } = require("../helpers/test-server"); const [port1, port2] = require("../ports-map")["cross-origin-request"]; describe("cross-origin requests", () => { @@ -217,4 +218,25 @@ describe("cross-origin requests", () => { htmlServer.close(); } }); + + it("should allow localhost for no-cors cross-site requests", async () => { + const { page, server } = await startServer({ + allowedHosts: "auto", + port: 0, + }); + const { port } = server.options; + await page.goto("about:blank"); + await page.evaluate((port) => { + const iframe = document.createElement("iframe"); + const html = ` + + `; + const blob = new Blob([html], { type: "text/html" }); + iframe.src = URL.createObjectURL(blob); + document.body.append(iframe); + }, port); + await page.waitForTimeout(2000); + const res = await page.goto(`http://localhost:${port}/main.js`); + expect(res.status()).toBe(200); + }); });