[英]Limit fetch results from javascript fetch
是否有类似于q=sort&
或q=created:&
的函数来限制 JavaScript 提取的结果数量?
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => { }
当然,最好的解决方案是,如果https://jsonplaceholder.typicode.com/posts
端点记录了您可以发送的限制或过滤参数。
假设结果是一个数组,或包含一个数组,第二好的解决方案是filter
结果(应用标准)和/或slice
结果(仅应用限制):
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...
});
来自https://developer.mozilla.org/en-US/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 种可能性:
您可以将有效负载添加到提取的正文中,请参见上文。
您可以简单地对其进行 url 编码。
在 res.json()) .then((data) => { } ... 你可以过滤你想要的数据。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.