【问题标题】:Problem with Axios Get request - might be an Asynchronous problemAxios Get 请求的问题 - 可能是异步问题
【发布时间】:2020-09-17 03:43:16
【问题描述】:

我似乎遇到了异步问题。我在整个应用程序中使用 react、express、sequelize 和 mariadb。我在前端使用 axios 来发出获取请求。但是,get 请求总是返回一个空值。但是,在我的后端代码中,我知道请求正在调用数据库 findAll()。

前端(React/Axios)

componentDidMount() {
   this.getPets();
}

 getPets = async () => {
    try {
        const resp = await axios.get('/getdogs');
        this.setState({ pets: resp.body });
        console.log(resp.data);
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }

server.js

app.get('/getdogs', (req, res) => {
  console.log("IN THE FUNCTION");
  const pets = db.getPets();
  console.log("All pets:", JSON.stringify(pets, null, 2));

  res.send(pets);
});

数据库.js

async function getPets() {
  const pets = await Pets.findAll();
  console.log("All pets:", JSON.stringify(pets, null, 2));
  return JSON.stringify(pets, null, 2);
}

server.js 的输出

nodemon] starting `node server.js`
Listening on port 5000
IN THE FUNCTION
All pets: {}
warning: please use IANA standard timezone format ('Etc/GMT0')
warning: please use IANA standard timezone format ('Etc/GMT0')
Executing (default): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Pets` AS `Pets`;
All pets: [
  {
    "id": 1,
    "name": "HULK",
    "createdAt": "2020-09-15T23:09:43.000Z",
    "updatedAt": "2020-09-15T23:09:43.000Z"
  },
  {
    "id": 2,
    "name": "Martha",
    "createdAt": "2020-09-15T23:09:43.000Z",
    "updatedAt": "2020-09-15T23:09:43.000Z"
  },
  {
    "id": 3,
    "name": "Bernie",
    "createdAt": "2020-09-15T23:09:43.000Z",
    "updatedAt": "2020-09-15T23:09:43.000Z"
  }
]

【问题讨论】:

    标签: asynchronous promise async-await axios sequelize.js


    【解决方案1】:
    1. axios 响应没有body 属性。响应在data 属性中,请参阅Response schema
     this.setState({ pets: resp.data });
            console.log(resp.data);
    
    1. 您还没有等待 DB 的结果:
    db.getPets().then(pets => {
      console.log("All pets:", JSON.stringify(pets, null, 2));
    
      res.send(pets);
    });
    

    【讨论】:

    • 谢谢!我只是在阅读有关使用 .then 承诺等待的内容。
    猜你喜欢
    • 2020-02-15
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2023-03-12
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多