fix: 用户手动输入query条件导致的搜索异常问题

This commit is contained in:
2026-08-14 21:28:41 +08:00
parent b3038603e8
commit 555135aedb

View File

@@ -10,15 +10,9 @@ const searchParams = Astro.url.searchParams;
const t = searchParams.get("t") ?? ""; const t = searchParams.get("t") ?? "";
const c = searchParams.get("c") ?? ""; const c = searchParams.get("c") ?? "";
const [{data: categories}, {data: tags}, {data: posts}] = await Promise.all([ const [{data: categories}, {data: tags}] = await Promise.all([
http.get<ApiResponse<CategoriesStats[]>>("categories/stats"), http.get<ApiResponse<CategoriesStats[]>>("categories/stats"),
http.get<ApiResponse<Tag[]>>("posts/tags"), http.get<ApiResponse<Tag[]>>("posts/tags"),
http.get<ApiResponse<Post[]>>("posts/search", {
searchParams: {
category_code: c ?? "",
tag_code: t ?? "",
}
}),
] as const) ] as const)
let f_count = 0 let f_count = 0
@@ -36,6 +30,14 @@ const findTag = tags.find(item => {
return item.code === t return item.code === t
}) })
// 搜索条件必须匹配 不允许非法值
const {data:posts} = await http.get<ApiResponse<Post[]>>("posts/search", {
searchParams: {
category_code: findCategory?.code ?? "",
tag_code: findTag?.code ?? "",
}
})
const count = posts.length const count = posts.length
const pageTitle = const pageTitle =
@@ -49,24 +51,33 @@ const pageDescription =
: `浏览${pageTitle}相关文章,共 ${count} 篇。` : `浏览${pageTitle}相关文章,共 ${count} 篇。`
const buildSearchUrl = (type: 'category' | 'tag', code: string) => { const buildSearchUrl = (type: 'category' | 'tag', code: string) => {
const params = { const params = new URLSearchParams()
t: t,
c: c, if (findTag?.code) {
params.set('t', findTag.code)
}
if (findCategory?.code) {
params.set('c', findCategory.code)
} }
if (type === 'category') { if (type === 'category') {
params.c = c === code ? "" : code if (c === code) {
params.delete('c')
} else { } else {
params.t = t === code ? "" : code params.set('c', code)
}
} else {
if (t === code) {
params.delete('t')
} else {
params.set('t', code)
}
} }
const searchParams = new URLSearchParams( const query = params.toString()
Object.entries(params).filter(([, value]) => value !== '')
);
const query = searchParams.toString(); return query ? `/search?${query}` : '/search'
return query ? `/search?${query}` : '/search';
} }
--- ---
<Layout title={pageTitle} description={pageDescription}> <Layout title={pageTitle} description={pageDescription}>