修复随机文章

This commit is contained in:
2026-06-18 20:36:03 +08:00 Unverified
parent 41854a128d
commit 7dc7cd9e73
2 changed files with 35 additions and 12 deletions
+14
View File
@@ -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
View File
@@ -1,13 +1,22 @@
function randomPost() {
fetch('/sitemap.xml').then(res => res.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml")).then(data => {
let ls = data.querySelectorAll('url loc');
let locationHref,locSplit;
do {
locationHref = ls[Math.floor(Math.random() * ls.length)].innerHTML
locSplit = locationHref.split('/')[3] || ''
} while (locSplit !== 'posts');
//若所有文章都如 https://…….com/posts/2022/07/…… 格式,主域名后字符是 posts,则循环条件改为:
//while (locSplit !== 'posts');
location.href = locationHref
})
}
fetch('/api/posts.json')
.then(res => {
if (!res.ok) throw new Error(`Failed to load posts: ${res.status}`);
return res.json();
})
.then(posts => {
const postLinks = posts
.map(post => post && post.href)
.filter(href => typeof href === 'string' && href.startsWith('/posts/'));
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);
});
}