Skip to content

Commit 2a6b6fa

Browse files
alan-agius4amishne
authored andcommitted
fix(platform-server): ensure origin has a trailing slash when parsing url
The origin did not have a trailing slash, which caused parsing issues for relative URLs. Fixes #68322
1 parent 982e3cc commit 2a6b6fa

2 files changed

Lines changed: 26 additions & 5 deletions

File tree

packages/platform-server/src/location.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,16 @@ import {INITIAL_CONFIG} from './tokens';
2424
* @param origin The origin to use for resolving the URL.
2525
* @returns The parsed URL.
2626
*/
27-
function parseUrl(urlStr: string, origin: string): URL {
28-
// If the URL is empty or start with a `/` it is a pathname relative to the origin
29-
// otherwise it's an absolute URL.
30-
const urlToParse = urlStr.length === 0 || urlStr[0] === '/' ? origin + urlStr : urlStr;
27+
export function parseUrl(urlStr: string, origin: string): URL {
28+
if (URL.canParse(urlStr)) {
29+
return new URL(urlStr);
30+
}
31+
32+
if (urlStr && urlStr[0] !== '/') {
33+
urlStr = `/${urlStr}`;
34+
}
3135

32-
return new URL(urlToParse);
36+
return new URL(origin + urlStr);
3337
}
3438

3539
/**

packages/platform-server/test/platform_location_spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,26 @@ import {PlatformLocation, ɵgetDOM as getDOM} from '@angular/common';
1111
import {destroyPlatform} from '@angular/core';
1212
import {INITIAL_CONFIG, platformServer} from '@angular/platform-server';
1313

14+
import {parseUrl} from '../src/location';
15+
1416
(function () {
1517
if (getDOM().supportsDOMEvents) return; // NODE only
1618

19+
describe('parseUrl', () => {
20+
it('should resolve relative paths against origin', () => {
21+
const url = parseUrl('/deep/path?query#hash', 'http://test.com');
22+
expect(url.href).toBe('http://test.com/deep/path?query#hash');
23+
expect(url.search).toBe('?query');
24+
expect(url.hash).toBe('#hash');
25+
});
26+
27+
it('should resolve absolute URLs ignoring origin', () => {
28+
const url = parseUrl('http://other.com/deep/path', 'http://test.com');
29+
expect(url.href).toBe('http://other.com/deep/path');
30+
expect(url.origin).toBe('http://other.com');
31+
});
32+
});
33+
1734
describe('PlatformLocation', () => {
1835
beforeEach(() => {
1936
destroyPlatform();

0 commit comments

Comments
 (0)