fix(postData): do not require content type when retrieving post data (#5736)

This commit is contained in:
Pavel Feldman 2021-03-05 21:25:14 -08:00 committed by GitHub
parent b5aeba90a6
commit 9e20566244
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 4 deletions

View File

@ -113,9 +113,6 @@ export class Request extends ChannelOwner<channels.RequestChannel, channels.Requ
return null;
const contentType = this.headers()['content-type'];
if (!contentType)
return null;
if (contentType === 'application/x-www-form-urlencoded') {
const entries: Record<string, string> = {};
const parsed = new URLSearchParams(postData);
@ -124,7 +121,11 @@ export class Request extends ChannelOwner<channels.RequestChannel, channels.Requ
return entries;
}
return JSON.parse(postData);
try {
return JSON.parse(postData);
} catch (e) {
throw new Error('POST data is not a valid JSON object: ' + postData);
}
}
headers(): Headers {

View File

@ -118,3 +118,40 @@ it('should return correct postData buffer for utf-8 body', async ({page, server}
expect(request.postDataBuffer().equals(Buffer.from(JSON.stringify(value), 'utf-8'))).toBe(true);
expect(request.postDataJSON()).toBe(value);
});
it('should return post data w/o content-type', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest('**'),
page.evaluate(({url}) => {
const request = new Request(url, {
method: 'POST',
body: JSON.stringify({ value: 42 }),
});
request.headers.set('content-type', '');
return fetch(request);
}, {url: server.PREFIX + '/title.html'})
]);
expect(request.postDataJSON()).toEqual({ value: 42 });
});
it('should throw on invalid JSON in post data', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest('**'),
page.evaluate(({url}) => {
const request = new Request(url, {
method: 'POST',
body: '<not a json>',
});
return fetch(request);
}, {url: server.PREFIX + '/title.html'})
]);
let error;
try {
request.postDataJSON();
} catch (e) {
error = e;
}
expect(error.message).toContain('POST data is not a valid JSON object: <not a json>');
});