Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API doesn't work with non-English characters in Microsoft Edge

I'm trying to send POST request to API using JavaScript Fetch API. Everything works fine in Chrome, FF, IE 11 (use polyfill) but doesn't work in Microsoft Edge (Console & Network tabs are empty). It works only when I send latin text as params. For example when I run this code:

fetch(API_URL, {
  method: 'POST',
  body: JSON.stringify({ str: '테스트'})
})
.then((data) => console.log(data))
.catch((err) => {
  console.error('fetch error:', error);
  throw error;
});

It doesn't do anything, but when I change value of "str" to "some latin text" then it works fine (sends correct request to API & receive response).

Issue on Microsoft website: fetch() with unicode characters in request body fails with TypeMismatchError

like image 758
Ihor Avatar asked Dec 06 '25 21:12

Ihor


1 Answers

Internally, JavaScript strings are encoded as UTF-16. It looks like Edge does not convert to another encoding by default and throws a TypeMismatchError if it deems your body not compatible to the configured (or assumed?) Content-type.

A fix for this issue is to escape all non-ASCII characters in the JSON representation of the payload:

function encodePayload(payload) {
    return JSON.stringify(payload).
        replace(/[\u007F-\uFFFF]/g, function (c) {
            return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).substr(-4);
        });
}

fetch(API_URL, {
    method: 'POST',
    body: encodePayload({ str: '테스트'})
})
like image 57
rockpiper Avatar answered Dec 08 '25 11:12

rockpiper