Empty response when fetching JS
I can't figure out what the problem is. Initially, the request was sent via $. ajax (jQuery). Now you need to rewrite everything to JS. I looked through the headers and sent data - everything is identical. After debagging the server, I made sure that the server returns the correct response, but fetch simply does not see it, and returns SyntaxError: Unexpected end of input
.
Below is the code:
// Пример отправки POST запроса:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
//"Accept": "application/json, text/javascript, */*; q=0.01",
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON_to_URLEncoded(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
//Отправка запроса
postData('{url}', {...})
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
}).catch(error => {
// Handle error
console.error("Ошибка HTTP: " + error); //Вот тут ошибка SyntaxError: Unexpected end of input
});
Initially I thought it was an empty response because the server returns a non-JSON format. But no, everything should work. At least at least through jQuery works. Tell me what the problem is
0
1 answers
The problem was solved by changing the mode
parameter to cors
, instead of no-cors
.
0
Author: Rebellion, 2020-06-29 14:15:47