修复随机文章
This commit is contained in:
@@ -0,0 +1,14 @@
|
|||||||
|
import { getAllPosts } from '@/lib/posts';
|
||||||
|
|
||||||
|
export function GET() {
|
||||||
|
const posts = getAllPosts().map((post) => ({
|
||||||
|
title: post.title,
|
||||||
|
href: post.href,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return new Response(JSON.stringify(posts), {
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json; charset=utf-8',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
+21
-12
@@ -1,13 +1,22 @@
|
|||||||
function randomPost() {
|
function randomPost() {
|
||||||
fetch('/sitemap.xml').then(res => res.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml")).then(data => {
|
fetch('/api/posts.json')
|
||||||
let ls = data.querySelectorAll('url loc');
|
.then(res => {
|
||||||
let locationHref,locSplit;
|
if (!res.ok) throw new Error(`Failed to load posts: ${res.status}`);
|
||||||
do {
|
return res.json();
|
||||||
locationHref = ls[Math.floor(Math.random() * ls.length)].innerHTML
|
})
|
||||||
locSplit = locationHref.split('/')[3] || ''
|
.then(posts => {
|
||||||
} while (locSplit !== 'posts');
|
const postLinks = posts
|
||||||
//若所有文章都如 https://…….com/posts/2022/07/…… 格式,主域名后字符是 posts,则循环条件改为:
|
.map(post => post && post.href)
|
||||||
//while (locSplit !== 'posts');
|
.filter(href => typeof href === 'string' && href.startsWith('/posts/'));
|
||||||
location.href = locationHref
|
|
||||||
})
|
if (postLinks.length === 0) {
|
||||||
}
|
console.warn('No posts available for random navigation.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
location.href = postLinks[Math.floor(Math.random() * postLinks.length)];
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Random post navigation failed:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user