Пытаюсь отправить запрос на CRUD-операции на back-end через fetch(). Вот фрагмент кода:
// Добавляет новый объект
uploadAction(event) {
event.preventDefault()
const target = event.target;
//let formData = new FormData();
let newData = {
data: {
Email: target.emailSubmit.value,
Age: target.ageSubmit.value,
}
};
//formData.append('data', newData.data)
let requestOptions = {
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
},
method: "PUT",
//mode: 'cors',
//body: formData,
body: JSON.stringify(newData)
}
fetch(this.url + '/api/records', requestOptions)
.then(response => response.json())
.then(
(result) => {
alert("Perfect send data");
},
(error) => {
alert(error.message);
}
)
this.setState({
editable: !this.state.editable,
items: this.state.items
})
window.location.reload();
}
// Сохраняет изменения
saveAction(event, nameOfInputs, id) {
event.preventDefault();
let newData = {
data: {}
};
//let formData = new FormData();
let inputs = document.getElementsByName(nameOfInputs);
inputs.forEach(
input => {
let key = input.id.split('|')[1];
newData.data[key] = input.value;
}
)
//formData.append('data', newData.data);
let requestOptions = {
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
},
method: "POST",
mode: 'cors',
//body: formData,
body: JSON.stringify(newData),
}
fetch(this.url + '/api/records/' + id, requestOptions)
.then(function(response) {
return response.json();
})
.then(
(result) => {
alert("Perfect edit data");
},
(error) => {
alert(error.message);
}
)
this.setState({
editable: !this.state.editable,
items: this.state.items
})
window.location.reload();
}
// Удаляет пользователя
deleteUser = (event, id) => {
event.preventDefault();
console.log(id);
fetch(this.url + '/api/records/' + id, {
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
},
method:'DELETE'
})
.then(response => response.json())
.then(
(result) => {
return alert('Perfect delete!');
},
(error) => {
return alert('Error on delete ' + error.message);
}
)
this.setState({
editable: !this.state.editable,
items: this.state.items
})
window.location.reload();
}
Проблема:
примерно каждый второй запрос заканчивается ошибкой Failed to fetch, однако даже при ошибке операция добавить/изменить/удалить может сработать.
Что пробовал (в коде закомментил //):
- Отправлять данные через форму
- изменять типы запросов с POST на PUT и обратно
.then(response => response.json()
заменил на
.then(function(response) {
return response.json();
})
- Искал ответа в других темах: https://stackoverflow.com/questions/49477659/typeerror-failed-to-fetch-react-js https://stackoverflow.com/questions/56948938/react-fetch-failed-typeerror-failed-to-fetch-even-though-the-api-returns-dat
Прикрепляю видео моих действий, приводящих к ошибке
https://www.dropbox.com/s/shgsnpwk7ngzor4/2020-05-06%20at%2022-20-56.mp4?dl=0
P.S.: вероятно, проблема кроется на серверной части. Жаль, что к ней доступа не имею ((