使用 axios 获取前 json 项
Get the firsts json items with axios
我正在研究 API 的前端,我正在尝试获取 JSON 列表的前十个项目,例如:
[{"element1":"value", "element2":"value"}, {"element1":"other value", "element2":"other value"}, ...]
但我不知道如何用 Axios 做到这一点:/
我在 Axios 的文档或这个论坛上没有找到任何东西
感谢您的帮助:)
你说的叫分页,这个功能应该在后端实现。如果后端不支持分页,那你只需要使用常规的js数组方法,例如slice https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
好的,所以您要使用的是带有 Axios 的 headers。像这样:
// 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 从 header 获取数据并提供您的数据:
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
方法的更多信息 here
我正在研究 API 的前端,我正在尝试获取 JSON 列表的前十个项目,例如:
[{"element1":"value", "element2":"value"}, {"element1":"other value", "element2":"other value"}, ...]
但我不知道如何用 Axios 做到这一点:/
我在 Axios 的文档或这个论坛上没有找到任何东西
感谢您的帮助:)
你说的叫分页,这个功能应该在后端实现。如果后端不支持分页,那你只需要使用常规的js数组方法,例如slice https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
好的,所以您要使用的是带有 Axios 的 headers。像这样:
// 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 从 header 获取数据并提供您的数据:
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
方法的更多信息 here