Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Update FetchHttpClient to send empty string for empty POST/PUT/PATCH requests. #1527

Merged
merged 2 commits into from
Aug 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
});
});