Skip to content

Commit

Permalink
Fix User-Agent request header (#40)
Browse files Browse the repository at this point in the history
I thought the previous implementation would cause the undefined
User-Agent to be omitted from the request headers, but it was
actually being included (triggering CORS). I'm dumb. Added a test to
prevent this in the future.
  • Loading branch information
wKovacs64 authored Jun 26, 2018
1 parent 3e84520 commit bd2e320
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
9 changes: 4 additions & 5 deletions src/internal/haveibeenpwned/axiosInstance.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import Axios from 'axios';
import { name, version } from '../../../package.json';

// Add a custom User-Agent header when running outside the browser
const customUserAgent =
typeof navigator === 'undefined' ? `${name} ${version}` : undefined;

/**
* An Axios instance used for API queries. Not meant for general use.
*
Expand All @@ -14,6 +10,9 @@ export default Axios.create({
baseURL: 'https://haveibeenpwned.com/api',
headers: {
Accept: 'application/vnd.haveibeenpwned.v2+json',
'User-Agent': customUserAgent,
// Add a custom User-Agent header when running outside the browser
...(typeof navigator === 'undefined' && {
'User-Agent': `${name} ${version}`,
}),
},
});
7 changes: 6 additions & 1 deletion src/internal/haveibeenpwned/axiosInstance.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ describe('internal (haveibeenpwned): axiosInstance', () => {
// Node
global.navigator = undefined;
const axiosInstanceNode = require.requireActual('./axiosInstance').default;
expect(Object.keys(axiosInstanceNode.defaults.headers)).toContain(
'User-Agent',
);
expect(axiosInstanceNode.defaults.headers['User-Agent']).toBeTruthy();

jest.resetModules();
Expand All @@ -15,7 +18,9 @@ describe('internal (haveibeenpwned): axiosInstance', () => {
global.navigator = {};
const axiosInstanceBrowser = require.requireActual('./axiosInstance')
.default;
expect(axiosInstanceBrowser.defaults.headers['User-Agent']).toBeUndefined();
expect(Object.keys(axiosInstanceBrowser.defaults.headers)).not.toContain(
'User-Agent',
);

global.navigator = originalNavigator;
});
Expand Down

0 comments on commit bd2e320

Please sign in to comment.