修复随机文章
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() {
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user