[英]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.