我正在尝试对 API 进行 axios GET 调用以检索一些 JSON 数据。数据存储在具有多个对象的数组中,每个对象都包含相同的键。该数组中有数百个对象,但我只想返回前十个。我知道数据集返回后我可以将其截断,但我想知道是否有办法限制对 API 调用的响应量。
这是数据集的示例:
[
{
"userId": 1,
"id": 1,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"userId": 1,
"id": 2,
"title": "1984",
"author": "George Orwell"
},
{
"userId": 1,
"id": 3,
"title": "The Count of Monte Cristo",
"author": "Alexandre Dumas"
},
]
Run Code Online (Sandbox Code Playgroud)
我的 axios 请求也很简单:
router.get('/', (req, res) => {
axios.get(`https://jsonwebsit.info.com/posts`)
.then( response => {
res.send(response.data)
})
.catch(err => {
console.log('Error getting all data from API', err)
})
});
Run Code Online (Sandbox Code Playgroud)
实际上,您可以限制来自某个 API 端点的响应数量。
只需在发出请求时将params 作为对象添加为第二个参数即可。
例如:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/todos',{
params: {
_limit: 10
}
})
.then((res) => {
this.setState({
todos: res.data
});
})
}
Run Code Online (Sandbox Code Playgroud)
此处您将 jsonplaceholder API 的响应限制为 10。
您也可以致电https://jsonplaceholder.typicode.com/todos/?_limit=10并得到相同的结果。
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
20527 次 |
| 最近记录: |