我正在處理 API 的前端,我正在嘗試獲取 JSON 串列的前十項,例如:
[{"element1":"value", "element2":"value"}, {"element1":"other value", "element2":"other value"}, ...]
但我不知道如何使用 Axios 來做到這一點:/ 我在Axios' Docs 或在這個論壇上
謝謝你的幫助 :)
uj5u.com熱心網友回復:
你所說的叫做分頁,這個功能應該在后端實作。如果后端不支持分頁,那么你只需要使用常規的 js 陣列方法,例如 slice https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
uj5u.com熱心網友回復:
好的,那么您將要使用的是帶有 Axios 的標頭。像這樣:
// headers are like variables that tell your backend what it needs to know
const config = {
headers: {
numberOfElements: 5
}
}
axios.get('/apiendpoint', config)
.then((response) => {
// what your backend is sending the frontend
console.log(response);
})
然后在您的后端,您可以使用 express 從該標頭獲取資料并提供您的資料:
const express = require('express');
const app = express();
// here is your example data
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
app.get('/urlendpoint', (req, res) => {
// use the req.get method to get the header data
const numberOfElements = req.get('numberOfElements');
// now we can use the arrays .slice() method to get the first x elements of an array and send it in the response
res.send(numbers.slice(0, numberOfElements));
});
您可以在此處閱讀有關該.slice方法的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/450519.html
標籤:javascript 数组 反应 json axios
上一篇:為選擇欄位使用道具資料
