【问题标题】:Why am I getting [object Object] on my axios GET request?为什么我在我的 axios GET 请求中得到 [object Object]?
【发布时间】:2020-07-21 06:26:10
【问题描述】:

我正在制作一个 react-express 应用程序,并从 SQLite3 数据库中提取以下数据:

[
    {
        id:1,
        name: 'henry',
        photo: '/Photos/dog1.jpg'
    },
    {
        id:1,
        name: 'boris',
        photo: '/Photos/dog2.jpg'
    },
    {
        id:1,
        name: 'Borker',
        photo: '/Photos/dog3.jpg'
    }
]

后端工作正常,并在邮递员发出 GET 请求时返回上述对象。我正在使用以下设置:

//Route

router.get('/', (req,res) => {
    db.getDogs()
    .then(dogs => {
        res.json(dogs)
    })
})

//API

export const getDogs =  () => {
 axios.get('/v1/dogs')
    .then(res => {
        console.log(res.data) // **returns [object Object]**
        return res.data
    })
}

//API call in react component

import React from 'react'
import {getDogs} from '../api/indexApi'

class App extends React.Component {
  constructor(){
    super()
    this.state = {
      dogs:[]
    }
  }

  componentDidMount() {
    getDogs()
    .then(dogs => {
      this.setState({
        dogs:dogs
      })
    })
  }

问题是我正在提取的数据没有在浏览器中呈现,我认为这与我的 axios 获取请求有关 - 安慰记录来自该请求的响应给出了 [object Object]。对于如何解决这个问题,有任何的建议吗?谢谢。

【问题讨论】:

  • 试试console.log(res),你得到了什么?
  • 还把后端代码和前端牛区分开来,方便我们掌握
  • 你的函数 getDogs 没有返回任何东西
  • 您是否为axios 创建了baseURL?您需要提供完整的 URL axios.get('localhost:8000/api/dogs')
  • 它没有渲染,因为 getDogs 函数没有返回任何东西,就像 Ifaruki 说的那样。将第一行改为return axios.get('/v1/dogs')

标签: reactjs express axios


【解决方案1】:

在我看来,您没有提供完整的 API URL 到 axios,如果您还没有为 axios 创建 baseURL,只需提供完整的 URL localhost:800/api/dogs

export const getDogs =  () => {
 return axios.get('localhost:8000/v1/dogs')
    .then(res => {
        console.log(res.data)
        return res.data
    })
}

你应该很高兴! To create baseURL for axios, DRY

【讨论】:

  • 但是如果我想记录axios 返回的完整响应怎么办?在这个例子中,我想得到:console.log(res);
  • @ConstantineCh 只是返回 res 而不是 res.data。编码愉快!
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 2021-05-14
  • 1970-01-01
相关资源
最近更新 更多