如何从 Strapi 内容中获取随机记录 API
How to get random records from Strapi content API
我在 strapi 中有记录。我正在使用 strapi 内容 API。在我的前端,我只需要随机显示 2 条记录。为了限制,我使用了来自内容 API 的限制查询。但是随机获取我需要使用的关键字。官方文档没有提供任何相关细节 - https://strapi.io/documentation/v3.x/content-api/parameters.html#available-operators
没有API参数来获得随机结果。
因此:FrontEnd 是针对您的问题的推荐解决方案。
您需要创建一个随机请求范围,然后从该范围中获取一些随机物品。
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
const firstID = getRandomInt(restaurants.length);
const secondID = getRandomInt(3);
const query = qs.stringify({
id_in:[firstID,secondID ]
});
// request query should be something like GET /restaurants?id_in=3&id_in=6
一种可靠的方法是通过两个步骤:
- 获取记录总数
- 使用
_start
和_limit
参数获取记录数
// Untested code but you get the idea
// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
const { data: totalNumberPosts } = await axios.get('/posts/count');
// Fetch 20 posts
const _limit = 20;
// We need to be sure that we are not fetching less than 20 posts
// e.g. we only have 40 posts. We generate a random number that is 30.
// then we would start on 30 and would only fetch 10 posts (because we only have 40)
const _start = getRandomArbitrary(0, totalNumberPosts - _limit);
const { data: randomPosts } = await axios.get('/posts', { params: { _limit, _start } })
这种方法的问题是它需要两次网络请求,但对于我的需要,这不是问题。
我在 strapi 中有记录。我正在使用 strapi 内容 API。在我的前端,我只需要随机显示 2 条记录。为了限制,我使用了来自内容 API 的限制查询。但是随机获取我需要使用的关键字。官方文档没有提供任何相关细节 - https://strapi.io/documentation/v3.x/content-api/parameters.html#available-operators
没有API参数来获得随机结果。
因此:FrontEnd 是针对您的问题的推荐解决方案。
您需要创建一个随机请求范围,然后从该范围中获取一些随机物品。
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
const firstID = getRandomInt(restaurants.length);
const secondID = getRandomInt(3);
const query = qs.stringify({
id_in:[firstID,secondID ]
});
// request query should be something like GET /restaurants?id_in=3&id_in=6
一种可靠的方法是通过两个步骤:
- 获取记录总数
- 使用
_start
和_limit
参数获取记录数
// Untested code but you get the idea
// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
const { data: totalNumberPosts } = await axios.get('/posts/count');
// Fetch 20 posts
const _limit = 20;
// We need to be sure that we are not fetching less than 20 posts
// e.g. we only have 40 posts. We generate a random number that is 30.
// then we would start on 30 and would only fetch 10 posts (because we only have 40)
const _start = getRandomArbitrary(0, totalNumberPosts - _limit);
const { data: randomPosts } = await axios.get('/posts', { params: { _limit, _start } })
这种方法的问题是它需要两次网络请求,但对于我的需要,这不是问题。