Ответ 1
Ответ цепочки должен выглядеть примерно так, в частности, часть response.json
. Тогда вы должны получить Object
обратно в console.log
.
.then(response => response.json())
.then(response => {
console.log(response)
}
При использовании fetch:
fetch(REQUEST_URL, {
method: 'get',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) =>
{
response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
console.log(responseData);
});
}).catch(function(err) {
console.log(err);
})
.done();
Следующие работы работают, знаете ли вы, почему?:
JSON.parse(response._bodyText)
Ответ цепочки должен выглядеть примерно так, в частности, часть response.json
. Тогда вы должны получить Object
обратно в console.log
.
.then(response => response.json())
.then(response => {
console.log(response)
}
Fetch немного сложно разобраться. Я новичок в этом, так что не сбивайте меня с толку, если здесь есть пламя, но данные ответа - это еще одно обещание, и вам нужно вернуть данные ответа, а затем обработать это обещание еще одним оператором then, в котором вы можете, наконец, зарегистрировать ответ, также вы не получили какой-то ответ заявления в ваших обещаниях:
var makeRequest = function(){
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
return response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
addTestToPage(responseData.title);
return responseData;
})
.catch(function(err) {
console.log(err);
})
}
function addTestToPage(textToAdd){
var para = document.createElement("p");
var node = document.createTextNode(textToAdd);
para.appendChild(node);
var element = document.getElementsByTagName("body")[0];
element.appendChild(para);
}
makeRequest();
надеюсь, что поможет увидеть: https://jsfiddle.net/byz17L4L/
Вот как это в конечном итоге получилось в моем случае:
fetch('http://localhost:3001/questions', {
method: 'GET',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
.then(response => { return response.json();})
.then(responseData => {console.log(responseData); return responseData;})
.then(data => {this.setState({"questions" : data});})
.catch(err => {
console.log("fetch error" + err);
});
}
потому что вы не ответили response.json() в первом.
fetch(weatherIng + zipCode +apiKey)
.then(response => response.json())
.then(response => {
console.log(response.main);
this.setState({
weather: ((response.main.temp * (9/5))-459.67).toFixed(0),
humidity:((response.main.humidity * (9/5))-459.67).toFixed(0)
})
Будет считаться, что вы пытаетесь объявить что-то, если вы не вложите его в свой собственный:
.then(response => {
console.log(response.main);
}) . " around the this.setState