asynchronous - Axios Get 请求的问题 - 可能是异步问题

标签 asynchronous promise async-await axios sequelize.js

我似乎遇到了异步问题。我正在为整个应用程序使用 react、express、sequelize 和 mariadb。我在前端使用 axios 来发出 get 请求。但是,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);
    }
服务器.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"
  }
]

最佳答案

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

    关于asynchronous - Axios Get 请求的问题 - 可能是异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63924589/

    相关文章:

    ios - 异步下载多个文件与同步下载

    asp.net-mvc - 如何判断 MVC AsyncController 线程是否在 ASP.NET 池或 I/O 完成端口中执行

    javascript - 使用带有 Promise 的 sinon 进行单元测试

    java - Thrift 是否有针对 Java 的异步服务器端方法定义?

    python - Python Asyncio队列获取未收到消息

    angular - 如何创建从回调函数返回 promise 的函数

    javascript - Protractor Promise fn 不是一个函数

    node.js - UnhandledPromiseRejectionWarning 即使代码在 async/await 中有 try/catch

    c# - 下面的代码是否捕获了 TPL 中原始任务、延续任务和子任务的异常?

    .net - 新的 HttpClient 代理设置问题