【发布时间】: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?您需要提供完整的 URLaxios.get('localhost:8000/api/dogs')。 -
它没有渲染,因为 getDogs 函数没有返回任何东西,就像 Ifaruki 说的那样。将第一行改为
return axios.get('/v1/dogs')