Skip to content

Commit

Permalink
Prefer native URL instead of legacy url.resolve.
Browse files Browse the repository at this point in the history
  • Loading branch information
RubenVerborgh committed Dec 30, 2023
1 parent 5ff7960 commit f7c94f0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 21 deletions.
16 changes: 12 additions & 4 deletions index.js
Expand Up @@ -6,6 +6,8 @@ var Writable = require("stream").Writable;
var assert = require("assert");
var debug = require("./debug");

var hasNativeURL = typeof URL !== undefined;

// Create handlers that pass events from native requests
var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
var eventHandlers = Object.create(null);
Expand All @@ -15,12 +17,12 @@ events.forEach(function (event) {
};
});

// Error types with codes
var InvalidUrlError = createErrorType(
"ERR_INVALID_URL",
"Invalid URL",
TypeError
);
// Error types with codes
var RedirectionError = createErrorType(
"ERR_FR_REDIRECTION_FAILURE",
"Redirected request failed"
Expand Down Expand Up @@ -426,7 +428,7 @@ RedirectableRequest.prototype._processResponse = function (response) {
url.format(Object.assign(currentUrlParts, { host: currentHost }));

// Determine the URL of the redirection
var redirectUrl = url.resolve(currentUrl, location);
var redirectUrl = resolveUrl(location, currentUrl);

// Create the redirected request
debug("redirecting to", redirectUrl);
Expand Down Expand Up @@ -494,7 +496,7 @@ function wrap(protocols) {
}
input = parsed;
}
else if (URL && (input instanceof URL)) {
else if (hasNativeURL && (input instanceof URL)) {
input = urlToOptions(input);
}
else {
Expand Down Expand Up @@ -538,9 +540,15 @@ function wrap(protocols) {
return exports;
}

/* istanbul ignore next */
function noop() { /* empty */ }

function resolveUrl(relative, base) {
return !hasNativeURL ?
/* istanbul ignore next */
url.resolve(base, relative) :
(new URL(relative, base)).href;
}

// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
function urlToOptions(urlObject) {
var options = {
Expand Down
17 changes: 0 additions & 17 deletions test/test.js
Expand Up @@ -312,23 +312,6 @@ describe("follow-redirects", function () {
});
});

it("emits an error when url.resolve fails", function () {
app.get("/a", redirectsTo("/b"));
var urlResolve = url.resolve;
url.resolve = function () {
throw new Error();
};

return server.start(app)
.then(asPromise(function (resolve) {
http.get("http://localhost:3600/a").on("error", resolve);
}))
.then(function (error) {
url.resolve = urlResolve;
assert.equal(error.code, "ERR_FR_REDIRECTION_FAILURE");
});
});

it("emits an error when the request fails for another reason", function () {
app.get("/a", function (req, res) {
res.socket.write("HTTP/1.1 301 Moved Permanently\r\n");
Expand Down

0 comments on commit f7c94f0

Please sign in to comment.