Currently attempting to fetch some JSON to an API. I am testing my fetch requests using requestcatcher.com. Here is an example, which highlights the problem I am having:
fetch("https://example.requestcatcher.com",
{
method: "POST",
mode: "no-cors",
headers: new Headers({ "Accept":"application/json", "Content-Type":"application/json" }),
body: "{}"
});
Upon sending this request, I expected the request catcher API to receive the header Content-Type: application/json. However, this is not happening - the Content-Type keeps getting reset to text/plain;charset=UTF-8. This happens whether I pass in a Headers object or simply an Object. The Content-Type is also the only header to be modified in this way - the Accept header doesn't suffer this issue.
Interestingly, this substitution doesn't happen if I pass in Content-Type: application/x-www-form-urlencoded: that header, unlike application/json, is received unaltered by the request catcher. It seems to have an unique problem with application/json. I've seen no successful explanation online regarding why this would happen - if anyone is able to shed some light on this I would be much grateful.
This issue arises because of the
"no-cors"mode you're using in yourfetch()options. When making afetch()request with theno-corsmode, you cannot set theContent-Type headerto'application/json', as this mode allows very limited headers and theContent-Type headerfor this mode is locked to a few safe ones, like'text/plain'.Here's your remediated code: