Skip to content

Commit

Permalink
feat: add relative URI support for baseURL
Browse files Browse the repository at this point in the history
  • Loading branch information
Hotell committed Jul 31, 2020
1 parent 3313c9f commit 6f28fc8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,14 @@ export default (function create(/** @type {Options} */ defaults) {
}

if (options.baseURL) {
url = new URL(url, options.baseURL) + '';
const _ = options.baseURL;
const placeholder = 'https';
const regex = RegExp(placeholder + '?://');
const protocol = (regex.exec(_) || [''])[0];
const base = protocol ? _ : placeholder + ':' + _;

url = new URL(url, base) + '';
url = protocol ? url : url.replace(regex, '/');
}

if (options.params) {
Expand Down
25 changes: 25 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 6f28fc8

Please sign in to comment.