首页 > 解决方案 > 从 axios 获取对象数组时出错

问题描述

我正在传递一个对象数组(硬代码值)以使用 axios 发出 get 请求,但每次都会出现这样的错误:

在此处输入图像描述

在这方面需要帮助,我是反应 js 的新手。在我看来,我在制作对象数组时犯了错误,或者我认为我们不能将 const 传递给 axios?

函数和对象数组(硬编码值)

const api =
    [
        {
            "description": "",
            "durationday": "fullday",
            "end": "null",
            "id": 0,
            "location": "",
            "start": "null",
            "title": "",
        },
        {
            "description": "yaaa!",
            "durationday": "absent",
            "end": "10-04-2021 12:10:00",
            "id": 1,
            "location": "perth",
            "start": "10-04-2021 12:10:00",
            "title": "holiday",
        },
        {
            "description": "busy",
            "durationday": "fullday",
            "end": "10-22-2021 12:10:00",
            "id": 2,
            "location": "melbourne",
            "start": '10-19-2021 12:00:00',
            "title": "working",
        },
        {
            "description": "dd",
            "durationday": "halfday",
            "end": "10-24-2021 12:10:00",
            "id": 3,
            "location": "updated perth",
            "start": "10-24-2021 12:10:00",
            "title": "updated holiday",
        }
    ]



console.log(api)


const getEvents = () => {
    axios.get(api)
        .then(response => {

            console.log(response.data)

        })

    .catch(err => console.log("This is error for fetching", err))
   

}
useEffect(() => {
    getEvents()
}, []);

标签: javascriptreactjsjsonapiaxios

解决方案


这里有几件事可以发出 API REST 请求:

1-它是一个 GET 请求,要遵循 API REST 规则,您应该使用 GET 来检索资源,因此您不应该传递正文。

2- 发出 api 请求时必须使用的第一个参数是作为字符串的 url 端点,例如:axios.get(“/endpointPath”).then…。

3-要将所有数据发送到服务器,您可以将其作为 POST 请求来提交新数据。例如: axios.post(“/endpointPath”,body).then... 在这种情况下,body 可以是您的 api const(如果您不使用邮递员或其他客户端,则不需要将其作为 json 传递)

4-您可能会发现这很有用:https ://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/


推荐阅读