JavaScript Fetch 如何限制获取的结果数量

4

是否有类似于q=sort&q=created:&的函数,可以在JavaScript fetch中限制结果数量?

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((res) => res.json())
  .then((data) => { }

.filter 怎么样? - Arfeo
这个问题不应该被踩,问得好,描述得也好,我也在寻找同样的东西。 - logos_164
2个回答

4
当然,最好的解决方案是如果https://jsonplaceholder.typicode.com/posts端点文档化了可以发送的限制或过滤参数。
假设结果是一个数组或包含一个数组,则非常第二好的解决方案是过滤结果(应用条件)和/或切片结果(只应用限制)。
fetch('https://jsonplaceholder.typicode.com/posts')
    .then((res) => res.json())
    .then((data) => {
        data = data.filter(entry => entry.created > someValue) // Created after X
                   .slice(0, 1000);                            // Limit to 1000
        // ...use data...
    })
    .catch(error => {        // <=== Don't forget to handle errors
        // Handle error...
    });

注意:您的fetch调用缺少对res.ok的检查(不仅是您,很多人都犯了这个错误,以至于我在我的微不足道的博客上写了一篇文章):
fetch('https://jsonplaceholder.typicode.com/posts')
    .then((res) => {                                      // ***
        if (!res.ok) {                                    // ***
            throw new Error("HTTP error " + res.status);  // ***
        }                                                 // ***
    })                                                    // ***
    .then((res) => res.json())
    .then((data) => {
        data = data.filter(entry => entry.created > someValue)
                   .slice(0, 1000);
        // ...use data...
    })
    .catch(error => {
        // Handle error...
    });

-1

来自https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

postData(`http://example.com/answer`, {answer: 42})
  .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
  .catch(error => console.error(error));

function postData(url = ``, data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, same-origin, *omit
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses response to JSON
}

不确定您想要什么,所以这里有3个可能性:

  1. 您可以将有效载荷添加到fetch的主体中,如上所述。

  2. 您可以简单地对其进行URL编码。

  3. 在res.json().then((data)=> {} ...中,您可以过滤所需的数据。

希望这可以帮助您。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接