Skip to content

Commit

Permalink
fix: Update FetchHttpClient to send empty string for empty POST/PUT/P…
Browse files Browse the repository at this point in the history
…ATCH requests. (#1527)
  • Loading branch information
dcr-stripe authored Aug 24, 2022
1 parent c356496 commit 3c65dab
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/net/FetchHttpClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,19 @@ class FetchHttpClient extends HttpClient {
);
url.port = port;

// For methods which expect payloads, we should always pass a body value
// even when it is empty. Without this, some JS runtimes (eg. Deno) will
// inject a second Content-Length header. See https://github.com/stripe/stripe-node/issues/1519
// for more details.
const methodHasPayload =
method == 'POST' || method == 'PUT' || method == 'PATCH';
const body = requestData || (methodHasPayload ? '' : undefined);

const fetchFn = this._fetchFn || fetch;
const fetchPromise = fetchFn(url.toString(), {
method,
headers,
body: requestData || undefined,
body,
});

// The Fetch API does not support passing in a timeout natively, so a
Expand Down
55 changes: 55 additions & 0 deletions test/net/FetchHttpClient.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const expect = require('chai').expect;
const fetch = require('node-fetch');
const nock = require('nock');
const {Readable} = require('stream');
const {FetchHttpClient} = require('../../lib/net/FetchHttpClient');

Expand Down Expand Up @@ -56,4 +57,58 @@ describe('FetchHttpClient', () => {
});
});
});

describe('it sets a body value for empty POST requests', () => {
let capturedBody;

const patchedFetch = (url, params) => {
capturedBody = params.body;
return fetch(url, params);
};

nock('http://stripe.com')
.post('/test', '')
.reply(200);

const client = new FetchHttpClient(patchedFetch);
client.makeRequest(
'stripe.com',
80,
'/test',
'POST',
{},
'', // requestData
'http',
1000
);

expect(capturedBody).to.equal('');
});

describe('it does not set a body value for empty GET requests', () => {
let capturedBody;

const patchedFetch = (url, params) => {
capturedBody = params.body;
return fetch(url, params);
};

nock('http://stripe.com')
.get('/test')
.reply(200);

const client = new FetchHttpClient(patchedFetch);
client.makeRequest(
'stripe.com',
80,
'/test',
'GET',
{},
'', // requestData
'http',
1000
);

expect(capturedBody).to.be.undefined;
});
});

0 comments on commit 3c65dab

Please sign in to comment.