首页 > 解决方案 > 在 React 中使用 fetch 从 API 获取数据

问题描述

在 Panel.js 中,如何从我在 index.js 中编写的 API 获取数据?

Panel.js 在此处输入图像描述

index.js 在此处输入图像描述

ProfilePanel.js 在此处输入图像描述

标签: javascriptreactjsapiaxios

解决方案


您可以使用 javascript 获取 API

获取示例

fetch(`https://jsonplaceholder.typicode.com/posts?key=${key}&results=${results}`)
            .then((res) => { return res.json() })
            .then((data) => { 
                console.log(data)
                });
           })
}

发布示例

  let key = 'key'
  let results = 12;

  fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers : new Headers(),
      body:JSON.stringify({key: key, results: results})//use property short hand here
  }).then((res) => res.json())
  .then((data) =>  console.log(data))
  .catch((err)=>console.log(err))

推荐阅读