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
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: '테스트'})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With