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 Content-Length header calculation #299

Merged
merged 3 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 2 additions & 2 deletions lib/tumblr.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,8 @@ class Client {
// Otherwise, we'll JSON encode the body
const requestBody = JSON.stringify(Object.fromEntries(data.entries()));
request.setHeader('Content-Type', 'application/json');
request.setHeader('Content-Length', requestBody.length);
request.write(requestBody);
request.setHeader('Content-Length', Buffer.byteLength(requestBody, 'utf8'));
request.write(requestBody, 'utf8');
}
}

Expand Down
20 changes: 19 additions & 1 deletion test/tumblr.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ describe('tumblr.js', function () {

describe('post request expected headers', () => {
it('with body', async () => {
const body = '{"foo":"bar"}';
const client = new TumblrClient({
...DUMMY_CREDENTIALS,
baseUrl: DUMMY_API_URL,
Expand All @@ -297,6 +298,7 @@ describe('tumblr.js', function () {
accept: 'application/json',
'user-agent': `tumblr.js/${tumblr.Client.version}`,
'content-type': 'application/json',
'content-length': Buffer.byteLength(body, 'utf-8').toString(),
authorization: (value) => {
return [
value.startsWith('OAuth '),
Expand All @@ -311,13 +313,29 @@ describe('tumblr.js', function () {
},
},
})
.post('/', '{"foo":"bar"}')
.post('/', body)
.reply(200, { meta: {}, response: {} });

assert.isOk(await client.postRequest('/', { foo: 'bar' }));
scope.done();
});

it('with unicode in body', async () => {
const body = '{"powerup":"🍄"}';
const client = new TumblrClient({
...DUMMY_CREDENTIALS,
baseUrl: DUMMY_API_URL,
});
const scope = nock(client.baseUrl, {
reqheaders: { 'content-length': Buffer.byteLength(body, 'utf-8').toString() },
})
.post('/', body)
.reply(200, { meta: {}, response: {} });

assert.isOk(await client.postRequest('/', { powerup: '🍄' }));
scope.done();
});

['data', 'data64'].forEach((dataField) => {
it(`with body and ${dataField}`, async () => {
const client = new TumblrClient({
Expand Down
Loading