From ed365e927cb5cc3f79c5564676d40463a39e79de Mon Sep 17 00:00:00 2001 From: Martin Hochel Date: Fri, 31 Jul 2020 17:44:58 +0200 Subject: [PATCH] feat: add relative URI support for baseURL --- src/index.js | 14 +++++++++++++- test/index.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 39f523b..ed77dcf 100644 --- a/src/index.js +++ b/src/index.js @@ -178,7 +178,19 @@ export default (function create(/** @type {Options} */ defaults) { } if (options.baseURL) { - url = new URL(url, options.baseURL) + ''; + const _ = options.baseURL; + const placeholder = 'http'; + const regex = RegExp(placeholder + 's?://'); + /** + * @type {string | null | RegExpExecArray} + */ + let protocol = regex.exec(_); + if (protocol) protocol = protocol[0]; + + const base = protocol ? _ : placeholder + ':' + _; + + url = new URL(url, base) + ''; + url = protocol ? url : url.replace(regex, '/'); } if (options.params) { diff --git a/test/index.test.js b/test/index.test.js index 2682d3d..13b0d37 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -98,6 +98,31 @@ describe('redaxios', () => { window.fetch = oldFetch; } }); + + it('should resolve baseURL for relative URIs', async () => { + const oldFetch = window.fetch; + try { + window.fetch = jasmine + .createSpy('fetch') + .and.returnValue(Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('') })); + const req = axios.get('/bar', { + baseURL: '/foo' + }); + expect(window.fetch).toHaveBeenCalledTimes(1); + expect(window.fetch).toHaveBeenCalledWith( + '/foo/bar', + jasmine.objectContaining({ + method: 'get', + headers: {}, + body: undefined + }) + ); + const res = await req; + expect(res.status).toEqual(200); + } finally { + window.fetch = oldFetch; + } + }); }); describe('options.headers', () => {