首页 > 解决方案 > 让 Axios 限制响应的数量

问题描述

我正在尝试对 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"
  },
]

我的 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)
        })
});

标签: reactjsapiaxios

解决方案


实际上,您可以限制来自某个 API 端点的响应数量。

只需在发出请求时将参数作为对象添加为第二个参数。

例如:

componentDidMount() {
  axios.get('https://jsonplaceholder.typicode.com/todos',{
    params: {
      _limit: 10
     }
  })
    .then((res) => {
      this.setState({
        todos: res.data
      });
    })
}

在这里,您将来自 jsonplaceholder API 的响应限制为 10。

你也可以打电话https://jsonplaceholder.typicode.com/todos/?_limit=10,得到同样的结果。

希望能帮助到你。


推荐阅读