Skip to content
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
12 changes: 11 additions & 1 deletion packages/fetch/src/utils/form-data.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {randomBytes} from 'crypto';
import { iterateMultipart } from '@web3-storage/multipart-parser';
import { FormData } from '../package.js';
import {isBlob} from './is.js';

const carriage = '\r\n';
Expand Down Expand Up @@ -86,8 +87,17 @@ export function getFormDataLength(form, boundary) {
/**
* @param {Body & {headers?:Headers}} source
*/
export const toFormData = async ({ body, headers }) => {
export const toFormData = async (source) => {
let { body, headers } = source;
const contentType = headers?.get('Content-Type') || ''

if (contentType.startsWith('application/x-www-form-urlencoded') && body != null) {
const form = new FormData();
let bodyText = await source.text();
new URLSearchParams(bodyText).forEach((v, k) => form.append(k, v));
return form;
}

const [type, boundary] = contentType.split(/\s*;\s*boundary=/)
if (type === 'multipart/form-data' && boundary != null && body != null) {
const form = new FormData()
Expand Down
34 changes: 34 additions & 0 deletions packages/fetch/test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -1500,6 +1500,25 @@ describe('node-fetch', () => {
});
});

it('should support URLSearchParams as POST body', () => {
const params = new URLSearchParams();
params.set('key1', 'value1');
params.set('key2', 'value2');

const url = `${base}multipart`;
const options = {
method: 'POST',
body: params
};

return fetch(url, options).then(res => res.json()).then(res => {
expect(res.method).to.equal('POST');
expect(res.headers['content-type']).to.startWith('application/x-www-form-urlencoded');
expect(res.body).to.contain('key1=');
expect(res.body).to.contain('key2=');
});
});

it('should allow POST request with object body', () => {
const url = `${base}inspect`;
// Note that fetch simply calls tostring on an object
Expand Down Expand Up @@ -1548,6 +1567,21 @@ describe('node-fetch', () => {
});
});

it('constructing a Request with URLSearchParams should provide formData()', () => {
const parameters = new URLSearchParams();
parameters.append('key', 'value');
const request = new Request(base, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: parameters,
});
return request.formData().then(formData => {
expect(formData.get('key')).to.equal('value');
});
});

it('should allow POST request with URLSearchParams as body', () => {
const parameters = new URLSearchParams();
parameters.append('a', '1');
Expand Down