简体   繁体   English

无法从API正确获取数据

[英]Cannot fetch properly data from API

I am currently trying out React for a future project and trying to get myself up to speed on it. 我目前正在为将来的项目尝试React,并努力使自己快速上手。

Bear with me, due to some circumstances I didn't code for 2 years so I am extremely rusty. 忍受我,由于某些情况,我有两年没有写代码了,所以我非常生锈。

Anyway, I need to get React to properly fetch some data about tasks written up, but no matter what I try it just doesn't work. 无论如何,我需要让React正确地获取一些有关编写的任务的数据,但是无论我尝试什么,都行不通。 I have a function written as 我有一个写为

  getDataFromDb = () => {
fetch("http://127.0.0.1:8080/api/getTask")
  .then(response => response.json())
  .then(data => this.setState({ tasks: data.tasks, isLoading: false }))
  .catch(error => this.setState({error, isLoading: false}));
};

Now my output inside the JSX file 现在我的输出在JSX文件中

<React.Fragment>
  <h1>Random User</h1>
  {error ? <p>{error.message}</p> : null}
  {!isLoading ? (
    tasks.map(task => {
      const { title, description } = task;
      return (
        <div key={title}>
          <p>Title: {title}</p>
          <p>Desc: {description}</p>
          <hr />
        </div>
      );
    })

  ) : (
    <h3>Loading...</h3>
  )}
</React.Fragment>

No matter what I try with my own database, it just doesn't want to work with React. 无论我尝试使用自己的数据库如何,它都不想使用React。 I try API calls through Postman and everything gets sent and received without any problems, but React sends out an error "Failed to fetch". 我尝试通过Postman进行API调用,所有内容都被发送和接收,没有任何问题,但是React发出一个错误“无法获取”。

In my server.js I have the following api call written 在我的server.js中,我编写了以下api调用

router.get("/getTask", (req, res) => {
Task.find((err, task) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, task: task });
  });
});

I have scoured Internet and Stack for some answers and examples, and, the dumbest thing is, if I use an external API (such as " https://hn.algolia.com/api/v1/search?query=redux "), or any other, honestly, then it works fine. 我已经在Internet和Stack上搜索了一些答案和示例,最愚蠢的是,如果我使用外部API(例如“ https://hn.algolia.com/api/v1/search?query=redux “) ,或者其他任何内容,那么效果很好。 If it makes any difference, I use mLabs sandbox for MongoDB. 如果有什么不同,我可以在MongoDB中使用mLabs沙箱。

Any suggestions? 有什么建议么? Been stuck on this for the last 5 hours or so. 最近5个小时左右一直停留在此。

Your fetch request seems to be going to a localhost address and port. 您的提取请求似乎要转到本地主机地址和端口。 Make sure CORS is is set up correctly on your server to allow for incoming connections from the same address with a different port. 确保在服务器上正确设置了CORS,以允许来自同一地址的不同端口的传入连接。 Postman usually works for any server set up correctly regardless of CORS settings. 不管CORS设置如何,Postman通常都能正确地用于任何服务器设置。 I'm not sure about fetch, but with axios, if you print the error object, it should give you a lot more information to work with. 我不确定如何获取,但是使用axios,如果您打印错误对象,它将为您提供更多信息。

In addition, stever's comment is also correct in that tasks is not defined since you're not using this state task. 另外,stever的注释也是正确的,因为您没有使用此状态任务,因此未定义任务。

You need to call getDataFromDb() inside your component at any point during the lifecycle or if it's tied to an event, such as onClick on a button etc. 在生命周期中的任何时候,或者与事件相关的事件(例如onClick on button等getDataFromDb()您都需要在组件内部调用getDataFromDb()

If you need it to load initially and your component is a function you can do the following 如果您需要它首先加载并且您的组件是一个函数,则可以执行以下操作

import React, {useState} from 'react;

function Component() {
 useState(() => {
   getDataFromDb,[])
return (
 <React.Fragment>
  <h1>Random User</h1>
  {error ? <p>{error.message}</p> : null}
  {!isLoading ? (
    tasks.map(task => {
      const { title, description } = task;
        <div key={title}>
          <p>Title: {title}</p>
          <p>Desc: {description}</p>
          <hr />
        </div>
     })

   ) : (
    <h3>Loading...</h3>
   )}
  </React.Fragment>
 )
}

or inside componentDidMount() if you are using a class component 或在componentDidMount()内部componentDidMount()如果您使用的是类组件)

The axios library is really good wrapper for fetching data :) axios库对于获取数据确实是一个很好的包装器:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM