feat(fetch): set content-length header if post data is present (#8979)

This commit is contained in:
Yury Semikhatsky 2021-09-17 09:00:18 -07:00 committed by GitHub
parent 8dd0387641
commit 43a690c204
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 1 deletions

View File

@ -136,7 +136,10 @@ export abstract class FetchRequest extends SdkObject {
postData = params.formData ? serilizeFormData(params.formData, headers) : params.postData;
else if (params.postData || params.formData)
throw new Error(`Method ${method} does not accept post data`);
if (postData) {
headers['content-length'] = String(postData.byteLength);
headers['content-type'] ??= 'application/octet-stream';
}
const fetchResponse = await this._sendRequest(requestUrl, options, postData);
const fetchUid = this._storeResponseBody(fetchResponse.body);
if (params.failOnStatusCode && (fetchResponse.status < 200 || fetchResponse.status >= 400))

View File

@ -430,6 +430,20 @@ it('should add default headers', async ({context, server, page}) => {
expect(request.headers['accept-encoding']).toBe('gzip,deflate,br');
});
it('should send content-length', async function({context, asset, server}) {
const bytes = [];
for (let i = 0; i < 256; i++)
bytes.push(i);
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
context._request.post(server.EMPTY_PAGE, {
data: Buffer.from(bytes)
})
]);
expect(request.headers['content-length']).toBe('256');
expect(request.headers['content-type']).toBe('application/octet-stream');
});
it('should add default headers to redirects', async ({context, server, page}) => {
server.setRedirect('/redirect', '/empty.html');
const [request] = await Promise.all([
@ -726,6 +740,7 @@ it('should support application/x-www-form-urlencoded', async function({context,
expect(req.headers['content-type']).toBe('application/x-www-form-urlencoded');
const body = (await req.postBody).toString('utf8');
const params = new URLSearchParams(body);
expect(req.headers['content-length']).toBe(String(params.toString().length));
expect(params.get('firstName')).toBe('John');
expect(params.get('lastName')).toBe('Doe');
expect(params.get('file')).toBe('f.js');
@ -817,6 +832,7 @@ it('should support multipart/form-data with ReadSream values', async function({c
expect(error).toBeFalsy();
expect(serverRequest.method).toBe('POST');
expect(serverRequest.headers['content-type']).toContain('multipart/form-data');
expect(serverRequest.headers['content-length']).toContain('5498');
expect(fields['firstName']).toBe('John');
expect(fields['lastName']).toBe('Doe');
expect(files['readStream'].name).toBe('simplezip.json');