Fix `Request` input body being dropped when using `searchParams`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The request was recreated from the normalized options to apply the new URL, but those options carry no body for a `Request` input, so the body was silently lost and the server received an empty request. The input body is now carried over as a stream, which requires request stream support.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent d27ad21 · Browse files · 4 files·+136 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+136 added−1 removed
- tests:+123 added−0 removed
- other:+13 added−1 removed
Provenance
- Commit
b4bdecc- Tree
3364a90- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
d27ad21
4 files changed+136 added−1 removed
modified:source/core/Ky.ts+9 added-1 removed
480 unmodified lines481 }482 }483 484 // Recreate request with the updated URL. We already have all options in this.#options, including duplex.485+ // A `Request` input's body is only available as a stream, so keeping it requires request stream support.486+ const {body: inheritedBody, keepalive, mode} = this.request;487+ const canUseInheritedBody = supportsRequestStreams && !keepalive && mode !== 'no-cors';485- this.request = new globalThis.Request(url, this.#options as RequestInit);488+ this.request = new globalThis.Request(url, {489+ ...this.#options,490+ keepalive,491+ mode,492+ body: this.#options.body ?? (canUseInheritedBody ? inheritedBody : undefined),493+ } as RequestInit);494 }495 496 if (this.#options.onUploadProgress && typeof this.#options.onUploadProgress !== 'function') {497 throw new TypeError('The `onUploadProgress` option must be a function');721 unmodified linesmodified:source/types/options.ts+2 added
112 unmodified lines113 114 Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).115 116 When passing an object, setting a value to `undefined` deletes the parameter, while `null` values are preserved and converted to the string `'null'`.117+118+ When `input` is a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) with a body, the body is sent as a stream, which requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and HTTP/2 for HTTPS connections (in Chromium-based browsers). In environments without request stream support, when `keepalive` is true, or when the effective mode is `'no-cors'`, the inherited body is dropped. A compatible body passed explicitly with the `body` option is still used.119 */120 searchParams?: SearchParamsOption;121 122 /**361 unmodified linesmodified:test/main.ts+123 added
1461 unmodified lines1462 url + '?old=&foo=1#hash',1463 );1464 });1465 1466+test('searchParams preserves the body of a Request input', async t => {1467+ const server = await createHttpTestServer(t);1468+ server.post('/', (request, response) => {1469+ response.json({url: request.url, body: request.body});1470+ });1471+1472+ const request = new Request(server.url, {method: 'POST', body: fixture});1473+ const result = await ky(request, {searchParams: {foo: '1'}}).json<{url: string; body: string}>();1474+1475+ t.is(result.url, '/?foo=1');1476+ t.is(result.body, fixture);1477+});1478+1479+test('searchParams preserves the JSON body and headers of a Request input', async t => {1480+ const server = await createHttpTestServer(t);1481+ server.post('/', (request, response) => {1482+ response.json({url: request.url, body: request.body, custom: request.headers['x-custom']});1483+ });1484+1485+ const request = new Request(server.url, {1486+ method: 'POST',1487+ body: JSON.stringify({hello: 'world'}),1488+ headers: {'content-type': 'application/json', 'x-custom': 'unicorn'},1489+ });1490+ const result = await ky(request, {searchParams: {foo: '1'}}).json<{url: string; body: unknown; custom: string}>();1491+1492+ t.is(result.url, '/?foo=1');1493+ t.deepEqual(result.body, {hello: 'world'});1494+ t.is(result.custom, 'unicorn');1495+});1496+1497+test('searchParams with a Request input still prefers the body option', async t => {1498+ const server = await createHttpTestServer(t);1499+ server.post('/', (request, response) => {1500+ response.json({body: request.body, contentLength: request.headers['content-length']});1501+ });1502+1503+ const request = new Request(server.url, {method: 'POST', body: 'ignored'});1504+ const result = await ky(request, {body: fixture, searchParams: {foo: '1'}, keepalive: true}).json<{body: string; contentLength: string}>();1505+1506+ t.is(result.body, fixture);1507+ t.is(result.contentLength, String(fixture.length));1508+});1509+1510+test('searchParams preserves a Request input body across retries', async t => {1511+ let requestCount = 0;1512+ const server = await createHttpTestServer(t);1513+ server.post('/', (request, response) => {1514+ requestCount++;1515+ if (requestCount === 1) {1516+ response.sendStatus(500);1517+ return;1518+ }1519+1520+ response.json({body: request.body});1521+ });1522+1523+ const request = new Request(server.url, {method: 'POST', body: fixture});1524+ const result = await ky(request, {1525+ searchParams: {foo: '1'},1526+ retry: {limit: 1, methods: ['post'], delay: () => 0},1527+ }).json<{body: string}>();1528+1529+ t.is(requestCount, 2);1530+ t.is(result.body, fixture);1531+});1532+1533+test('searchParams drops an inherited Request input body with keepalive', async t => {1534+ const request = new Request('https://example.com', {method: 'POST', body: fixture});1535+1536+ await ky(request, {1537+ searchParams: {foo: '1'},1538+ keepalive: true,1539+ async fetch(request) {1540+ t.is(request.url, 'https://example.com/?foo=1');1541+ t.true(request.keepalive);1542+ t.is(request.body, null);1543+ return new Response();1544+ },1545+ });1546+});1547+1548+test('searchParams drops an inherited Request input body in no-cors mode', async t => {1549+ const request = new Request('https://example.com', {method: 'POST', body: fixture});1550+1551+ await ky(request, {1552+ searchParams: {foo: '1'},1553+ mode: 'no-cors',1554+ async fetch(request) {1555+ t.is(request.url, 'https://example.com/?foo=1');1556+ t.is(request.mode, 'no-cors');1557+ t.is(request.body, null);1558+ return new Response();1559+ },1560+ });1561+});1562+1563+test('searchParams preserves keepalive inherited from a Request input', async t => {1564+ const request = new Request('https://example.com', {method: 'POST', body: fixture, keepalive: true});1565+1566+ await ky(request, {1567+ searchParams: {foo: '1'},1568+ async fetch(request) {1569+ t.true(request.keepalive);1570+ t.is(request.body, null);1571+ return new Response();1572+ },1573+ });1574+});1575+1576+test('searchParams preserves no-cors mode inherited from a Request input', async t => {1577+ const request = new Request('https://example.com', {method: 'POST', body: fixture, mode: 'no-cors'});1578+1579+ await ky(request, {1580+ searchParams: {foo: '1'},1581+ async fetch(request) {1582+ t.is(request.mode, 'no-cors');1583+ t.is(request.body, null);1584+ return new Response();1585+ },1586+ });1587+});1588+1589 test('init hook deletion over merged defaults and input URL', async t => {1590 const server = await createHttpTestServer(t);1591 1592 server.get('/', (request, response) => {1439 unmodified linesmodified:readme.md+2 added
217 unmodified lines218 Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).219 220 When passing an object, setting a value to `undefined` deletes the parameter, while `null` values are preserved and converted to the string `'null'`.221 222+When `input` is a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) with a body, the body is sent as a stream, which requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and HTTP/2 for HTTPS connections (in Chromium-based browsers). In environments without request stream support, when `keepalive` is true, or when the effective mode is `'no-cors'`, the inherited body is dropped. A compatible body passed explicitly with the `body` option is still used.223+224 ##### baseUrl225 226 Type: `string | URL`227 1649 unmodified lines