Skip to content

Commit

Permalink
fix: should not throw when fetch a Request with post (#563)
Browse files Browse the repository at this point in the history
## 现象
使用 post method fetch 一个 Request 对象时会出现 `Cannot construct a Request with
a Request object that has already been used.` 错误。

## 原因
Request 的 constructor 会把入参的 request.body.stream.locked 变为 true,urllib 的
fetch 中已经使用参数 input new 了一个 Request,再调用 undici fetch 时参数还是 input,就会报错。

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Updated the fetch method to utilize a `Request` object for improved
request handling.
- Added a new test case to verify POST request functionality using the
`Request` class.

- **Chores**
	- Updated `.gitignore` to exclude the `.idea/` directory.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
MadCcc authored Dec 11, 2024
1 parent bf2b5b1 commit 6f9f353
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ test/fixtures/ts-cjs-es2021/*.js
test/fixtures/ts-esm/*.js
.eslintcache
.tshy*
.idea/
2 changes: 1 addition & 1 deletion src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ export class FetchFactory {
} as any as RawResponseWithMeta;
try {
await FetchFactory.#opaqueLocalStorage.run(internalOpaque, async () => {
res = await UndiciFetch(input, init);
res = await UndiciFetch(request);
});
} catch (e: any) {
updateSocketInfo(socketInfo, internalOpaque, e);
Expand Down
11 changes: 11 additions & 0 deletions test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
fetch, FetchDiagnosticsMessage, FetchFactory, FetchResponseDiagnosticsMessage,
} from '../src/fetch.js';
import { RequestDiagnosticsMessage, ResponseDiagnosticsMessage } from '../src/HttpClient.js';
import { Request } from 'undici';

describe('fetch.test.ts', () => {
let close: any;
Expand Down Expand Up @@ -109,4 +110,14 @@ describe('fetch.test.ts', () => {
assert(stats);
assert(Object.keys(stats).length > 0);
});

it('fetch request with post should work', async () => {
await assert.doesNotReject(async () => {
const request = new Request(_url, {
method: 'POST',
body: 'test-body',
});
await fetch(request);
}, /Cannot construct a Request with a Request object that has already been used/);
});
});

0 comments on commit 6f9f353

Please sign in to comment.