IT이야기

fetch response.json()에서 responseData = 정의되지 않음

cyworld 2022. 3. 19. 12:04
반응형

fetch response.json()에서 responseData = 정의되지 않음

가져오기 사용 시:

  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는 정신을 차리기가 좀 어렵다.나는 이것에 익숙하지 않기 때문에 여기서 불꽃이 튀더라도 나를 쏘지 않는다. 그러나 대응 데이터는 다른 약속이다. 그리고 당신은 응답 데이터를 반환해야 한다. 그리고 그 약속을 다른 약속과 처리해야 한다. 당신이 마침내 응답을 기록할 수 있는 다른 진술과 함께 말이다. 또한 당신은 당신의 약속에 몇 가지 답신문을 놓치고 있다.

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);
    });
}

그땐 당신이 응답하지 않았으니까.json().

import React, {useEffect} from 'react';

useEffect(() => {
    getRecipes();
  }, []);

  const getRecipes = async () => {
    const response = await fetch(
      `https://........`
    );
    const data = await response.json();
    console.log(data);

  • 이 방법을 사용하면 데이터를 쉽게 찾을 수 있다.
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

참조URL: https://stackoverflow.com/questions/33237200/fetch-response-json-gives-responsedata-undefined

반응형