Я хотел бы преобразовать функцию XMLHttpRequest для извлечения API. Но результат другой.
Есть некоторые вещи, которые я должен делать неправильно, но я не знаю, что:/
Мое обещание с XMLHttpRequest:
return new Promise(function (resolve, reject) {
let formData = new FormData($searchForm);
if (searchTerm.length) {
formData.append("search", searchTerm);
}
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
console.log(request);
resolve(request.responseText);
}
};
request.open($searchForm.method, $searchForm.action, true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.send(formData);
});
return (что я хочу):
XMLHttpRequest {onreadystatechange: reload/http://localhost: 3000/app_dev.php/r... ", статус: 200, statusText:" OK ", responseType:" ", response:" {"countMessage": "No product find" }
И моя функция с API-интерфейсом:
function searchReload() {
const formData = new FormData($searchForm);
const url = $searchForm.action;
const method = $searchForm.method;
if (searchTerm.length) {
formData.append('search', searchTerm);
}
const header = new Headers();
header.append('X-Requested-With', 'XMLHttpRequest');
return fetch(url, {
method: method,
header,
body: formData
}).then(function (response) {
return response;
});
}
searchReload()
.then(response => {
return console.log(response);
});
Эта функция возвращает:
Ответ {type: "basic", url: " http://localhost: 3000/app_dev.php/r...", перенаправлено: false, статус: 200, ok: true, statusText: "OK", заголовки: заголовки, bodyUsed: ложный }
Кто-нибудь может мне помочь? Я не знаю, в чем проблема, и почему я не могу ответить: "{" countMessage ":" Без поиска продукта "} к моему ответу :(
Спасибо, сообщество!
Вам нужно вызвать response.json()
чтобы прочитать тело:
return fetch(url, {
method: method,
header,
body: formData
}).then(function (response) {
// perhaps check the status before doing this!
return response.json();
});
Пример ниже того, что происходит с bodyUsed
Когда вы читаете тело
fetch('https://jsonplaceholder.typicode.com/posts/1').then(function(response) {
console.log(response.bodyUsed);
var res = response.json();
console.log(response.bodyUsed);
return res;
}).then(function(json) {
console.log(json)
});
console.log(response.text())
что вы получите?