it-source

여러 get 요청을 요청하는 API 가져오기

criticalcode 2023. 3. 27. 21:18
반응형

여러 get 요청을 요청하는 API 가져오기

한 번에 여러 GET URL을 가져오고 가져온 JSON 데이터를 React DOM 요소에 넣는 방법을 알고 싶습니다.

코드는 다음과 같습니다.

fetch("http://localhost:3000/items/get")
.then(function(response){
        response.json().then(
            function(data){
                ReactDOM.render(
                    <Test items={data}/>,
                    document.getElementById('overview')
                );}
        );
    })
.catch(function(err){console.log(err);});

단, 서버에서 추가 JSON 데이터를 가져와 이 모든 JSON 데이터가 서버에 전달된 ReactDOM을 렌더링하고 싶습니다.예를 들어 다음과 같습니다.

ReactDOM.render(
   <Test items={data} contactlist={data2} itemgroup={data3}/>,
   document.getElementById('overview')
);

이게 가능합니까?그렇지 않은 경우 여러 JSON 데이터를 렌더링 ReactDOM 요소로 가져오는 다른 솔루션은 무엇입니까?

그 때 해결되기 전에 모든 것을 실행하겠다는 약속을 믿으셔도 됩니다.jQuery에 익숙한 경우 jQuery Promits도 사용할 수 있습니다.

약속 있음.코드 실행을 계속하기 전에 모든 요청을 완료하도록 강제합니다.

Promise.all([
  fetch("http://localhost:3000/items/get"),
  fetch("http://localhost:3000/contactlist/get"),
  fetch("http://localhost:3000/itemgroup/get")
]).then(([items, contactlist, itemgroup]) => {
    ReactDOM.render(
        <Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
        document.getElementById('overview');
    );
}).catch((err) => {
    console.log(err);
});

그러나 아무리 힘들어도 현재 모든 브라우저에서 fetch가 구현되어 있지는 않기 때문에 요청을 처리하기 위해 추가 레이어를 만들 것을 강력히 권장합니다.여기서 fetch를 호출하거나 폴백을 사용할 수 있습니다.XmlHttpRequest또는jQuery아약스

그 밖에도 다음 웹 사이트를 꼭 보시길 권해드립니다.Redux반응 용기의 데이터 흐름을 처리합니다.셋업이 더 복잡해지겠지만 장차 성과가 있을 것이다.

2018년 8월 비동기/대기 업데이트

현재 주요 브라우저의 모든 최신 버전에 fetch가 구현되어 있으며 IE11을 제외하고 polyfill을 사용하지 않는 한 래퍼는 여전히 유용할 수 있습니다.

그 후, destructing이나 async/wait와 같은 새롭고 안정된 javascript 기능을 이용하면, 같은 문제에 대해 같은 솔루션을 사용할 수 있을 것입니다(아래 코드 참조).

언뜻 보기엔 좀 더 코드가 있는 것처럼 보일지 몰라도 사실은 더 깔끔한 접근법이라고 생각합니다.도움이 됐으면 좋겠다.

try {
  let [items, contactlist, itemgroup] = await Promise.all([
    fetch("http://localhost:3000/items/get"),
    fetch("http://localhost:3000/contactlist/get"),
    fetch("http://localhost:3000/itemgroup/get")
  ]);

  ReactDOM.render(
    <Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
      document.getElementById('overview');
  );
}
catch(err) {
  console.log(err);
};

json 형식 응답이 필요해서 직접 코드를 조금 추가했습니다.

Promise.all([
            fetch(url1).then(value => value.json()),
            fetch(url2).then(value => value.json())
            ])
            .then((value) => {
               console.log(value)
              //json response
            })
            .catch((err) => {
                console.log(err);
            });

일부 구현 사용Promise.all( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) 에서는 한 번에 여러 요청을 한 후 원하는 데이터를 사용하여 원하는 작업을 수행합니다.

Promise.all([
  fetch("http://localhost:3000/items/get1"),
  fetch("http://localhost:3000/items/get2"),
  fetch("http://localhost:3000/items/get3")
]).then(allResponses => {
  const response1 = allResponses[0]
  const response2 = allResponses[1]
  const response3 = allResponses[2]

  ...

})

예를 들어 여러 엔드포인트를 가져온 방법은 다음과 같습니다.

 const findAnyName = async() => {
const urls = ['https://randomuser.me/api/', 'https://randomuser.me/api/'];
  try{
    let res = await Promise.all(urls.map(e => fetch(e)))
    let resJson = await Promise.all(res.map(e => e.json()))
    resJson = resJson.map(e => e.results[0].name.first)
    console.log(resJson)
  }catch(err) {
    console.log(err)
  }
}
findAnyName()

다음은 JSFiddle에서 확인할 수 있는 완전한 예입니다.

또는 모든 URL을 배열로 선언합니다.이 어레이를 루프하여 단일 URL을 어레이 인덱스라고 합니다.

     constructor(props) {
        super(props);
        this.state = { World: [], Afghanistan: [], USA: [], Australia: [] };
    }                                                                           
                       
 const urls = [
            'https://corona.lmao.ninja/v2/all',
            'https://corona.lmao.ninja/v2/countries/afghanistan',
            'https://corona.lmao.ninja/v2/countries/usa',
            'https://corona.lmao.ninja/v2/countries/australia'
        ];
    
    Promise.all(urls.map(url =>
                fetch(url)
                    .then(checkStatus)  // check the response of our APIs
                    .then(parseJSON)    // parse it to Json
                    .catch(error => console.log('There was a problem!', error))
            ))
                .then(data => {
                    // assign to requested URL as define in array with array index.
                    const data_world = data[0];
                    const data_af = data[1];
                    const data_usa = data[2];
                    const data_aus = data[3];
                    this.setState({
                                World: data_world,
                                Afghanistan: data_af,
                                USA: data_usa,
                                Australia: data_aus
                            })
                })
   function checkStatus(response) {
            if (response.ok) {
                return Promise.resolve(response);
            } else {
                return Promise.reject(new Error(response.statusText));
            }
        }

    function parseJSON(response) {
        return response.json();
    }

결과

const { World, Afghanistan, USA, Australia} = this.state;

        console.log(World, Afghanistan, USA, Australia)

다음과 같은 작업을 할 수 있습니다.처음에는 양쪽 요구에 대해 fetch 직후에 결과를 메인 배열로 얻을 수 있습니다.

    Promise.all([
      fetch(
        "https://example.com/reviews/",
        requestOptionsDoc
      ).then((res1) => res1.json()),
      fetch(
        "https://example.com/reviews/",
        requestOptionsRel
      ).then((res2) => res2.json()),
    ])
      .then(([result1, result2]) => {
        if (result1.detail) {
          setDoctorReviewDetails("No review found.");
        } else {
          setDoctorReviewDetails(result1.data.comment);
        }
        if (result2.detail) {
          setRelativeReview("No review found.");
        } else {
          setRelativeReview(result2.data.comment);
        }
      })
      .catch((error) => console.log("error", error));

언급URL : https://stackoverflow.com/questions/46241827/fetch-api-requesting-multiple-get-requests

반응형