Skip to content

Commit

Permalink
fix(fetch-http-handler): omit body for HEAD/GET methods (#1698)
Browse files Browse the repository at this point in the history
  • Loading branch information
AllanZhengYP authored Nov 19, 2020
1 parent 8adfed1 commit 778b305
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
50 changes: 50 additions & 0 deletions packages/fetch-http-handler/src/fetch-http-handler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,56 @@ describe.skip(FetchHttpHandler.name, () => {
expect(requestCall[0]).toBe("https://foo.amazonaws.com:443/test/?bar=baz");
});

it("will omit body if method is GET", async () => {
const mockResponse = {
headers: { entries: jest.fn().mockReturnValue([]) },
blob: jest.fn().mockResolvedValue(new Blob()),
};
const mockFetch = jest.fn().mockResolvedValue(mockResponse);

(global as any).fetch = mockFetch;

const httpRequest = new HttpRequest({
headers: {},
hostname: "foo.amazonaws.com",
method: "GET",
path: "/",
body: "will be omitted",
});
const fetchHttpHandler = new FetchHttpHandler();

await fetchHttpHandler.handle(httpRequest, {});

expect(mockFetch.mock.calls.length).toBe(1);
const requestCall = mockRequest.mock.calls[0];
expect(requestCall[1].body).toBeUndefined();
});

it("will omit body if method is HEAD", async () => {
const mockResponse = {
headers: { entries: jest.fn().mockReturnValue([]) },
blob: jest.fn().mockResolvedValue(new Blob()),
};
const mockFetch = jest.fn().mockResolvedValue(mockResponse);

(global as any).fetch = mockFetch;

const httpRequest = new HttpRequest({
headers: {},
hostname: "foo.amazonaws.com",
method: "HEAD",
path: "/",
body: "will be omitted",
});
const fetchHttpHandler = new FetchHttpHandler();

await fetchHttpHandler.handle(httpRequest, {});

expect(mockFetch.mock.calls.length).toBe(1);
const requestCall = mockRequest.mock.calls[0];
expect(requestCall[1].body).toBeUndefined();
});

it("will not make request if already aborted", async () => {
const mockResponse = {
headers: {
Expand Down
9 changes: 6 additions & 3 deletions packages/fetch-http-handler/src/fetch-http-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,15 @@ export class FetchHttpHandler implements HttpHandler {
}
}

const port = request.port;
const { port, method } = request;
const url = `${request.protocol}//${request.hostname}${port ? `:${port}` : ""}${path}`;
// Request constructor doesn't allow GET/HEAD request with body
// ref: https://github.com/whatwg/fetch/issues/551
const body = method === "GET" || method === "HEAD" ? undefined : request.body;
const requestOptions: RequestInit = {
body: request.body,
body,
headers: new Headers(request.headers),
method: request.method,
method: method,
};

// some browsers support abort signal
Expand Down

0 comments on commit 778b305

Please sign in to comment.