javascript - 从 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()
}, []);
解决方案
这里有几件事可以发出 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/
推荐阅读
- python-3.x - 删除打开的文件
- laravel - 在 Laravel 中基于 AND 而不是 OR 过滤类别
- java - 使用 WebClient 时对 POST 请求正文进行单元测试
- python - 如何在更改标准输出时使用包装器覆盖打印功能
- vb.net - 使用 DataTable 中的日期进行过滤
- javascript - 使用 javascript 和 HTML 的表格布局
- c - 我的输出的第一个元素是错误的,我想编写一个将数组作为输入并将其反转的 C 函数
- elasticsearch - Reindex调用中的“include”参数中指定的字段数量是否有限制
- postgresql - 如何在 from 和 where 子句中使用相同的 psql 子查询?
- c# - 如何计算从组合框中选择的项目的票数