Skip to content

Commit

Permalink
fix: don't set Content-Length in XMLHttpRequest fn (#554)
Browse files Browse the repository at this point in the history
Setting the `Content-Length` request header in the context of an
XMLHttpRequest leads to the error:
```
Refused to set unsafe header "Content-Length"
```
This header is considered a forbidden request header that can't be set
with `setRequestHeader()`. I've confirmed that the initial
implementation was unnecessary:
#358 (comment).

See the XMLHttpRequest specs:
* [setRequestHeader()
method](https://xhr.spec.whatwg.org/#the-setrequestheader()-method)
* [Forbidden request
header](https://fetch.spec.whatwg.org/#forbidden-request-header)

[CR-6763](https://algolia.atlassian.net/browse/CR-6763)

[CR-6763]:
https://algolia.atlassian.net/browse/CR-6763?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
  • Loading branch information
jkaho authored Sep 3, 2024
1 parent 406d654 commit e3aaa8e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
8 changes: 6 additions & 2 deletions lib/utils/__tests__/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,11 @@ describe("request", () => {
expect(sent).toBe(true);
expect(navigator.sendBeacon).not.toHaveBeenCalled();
expect(open).toHaveBeenCalledTimes(1);
expect(setRequestHeader).toHaveBeenCalledTimes(2);
expect(setRequestHeader).toHaveBeenCalledTimes(1);
expect(setRequestHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json"
);
expect(open).toHaveBeenLastCalledWith("POST", url);
expect(send).toHaveBeenCalledTimes(1);
expect(send).toHaveBeenLastCalledWith(JSON.stringify(data));
Expand All @@ -162,7 +166,7 @@ describe("request", () => {
expect(navigator.sendBeacon).toHaveBeenCalledTimes(1);

expect(open).toHaveBeenCalledTimes(1);
expect(setRequestHeader).toHaveBeenCalledTimes(2);
expect(setRequestHeader).toHaveBeenCalledTimes(1);
expect(open).toHaveBeenLastCalledWith("POST", url);
expect(send).toHaveBeenCalledTimes(1);
expect(send).toHaveBeenLastCalledWith(JSON.stringify(data));
Expand Down
1 change: 0 additions & 1 deletion lib/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export const requestWithXMLHttpRequest: RequestFnType = (url, data) => {
req.addEventListener("timeout", () => resolve(false));
req.open("POST", url);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("Content-Length", `${serializedData.length}`);
req.send(serializedData);
});
};
Expand Down

0 comments on commit e3aaa8e

Please sign in to comment.