diff --git a/src/pages/api/posts.json.js b/src/pages/api/posts.json.js new file mode 100644 index 0000000..c7e8e44 --- /dev/null +++ b/src/pages/api/posts.json.js @@ -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', + }, + }); +} diff --git a/static/js/random.js b/static/js/random.js index 6989557..481ee1a 100644 --- a/static/js/random.js +++ b/static/js/random.js @@ -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 - }) -} \ No newline at end of file + 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); + }); +}