首页完善(后端)
# 07.首页完善(后端)+导航栏
首页完善(下)和导航栏模块
# 首页完善
创建src/app/api/create-chat/route.ts
写一个POST的异步请求,检测是否有登录,登陆后创建一个新的chat
import { createChat } from "@/db"
import { auth } from "@clerk/nextjs/server";
export async function POST(req:Request){
const {title,model} = await req.json()
const {userId} = await auth() //检测是否有登录
if (userId){
//1.创建一个chat
const newChat = await createChat(title,userId,model)
// 2.返回新创建的chat_id
return new Response(JSON.stringify({id:newChat?.id}),{status:200})
}
return new Response(null, {status:200})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
在首页输入字符,会自动创建一个新的页面
在supabase中可以看到创建了以对话内容为标题的数据
# 导航栏
在src/components/Navibar.tsx
文件中,声明'use client' 表示该文件被视为客户端捆绑的一部分
修改return部分的代码,创建按钮返回首页
此时效果如下
# 目录
使用useQuery
const {data: chats} = useQuery({
queryKey:['chats'],
queryFn:() => {
return axios.get(`/api/get-chats`)
},
enabled: !!user?.id
})
1
2
3
4
5
6
7
2
3
4
5
6
7
目录块
{/* 目录 */}
<div className='flex flex-col items-center justify-center gap-2 p-6'>
{chats?.data?.map((chat:ChatModel) =>(
<div
className = 'w-full h-10'
key={chat.id}
onClick={() => {
router.push(`/chats/${chat.id}`)
}}
>
<p className={`font-extralight text-sm line-clamp-1`}>{chat.title}</p>
</div>
) )}
</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
高亮设置:如果读取的是当前会话,给当前会话一个高亮
......
const pathname = usePathname()
......
<p className={`font-extralight text-sm line-clamp-1 ${pathname === `/chat/${chat.id} ` ? 'text-blue-700':''}`}>{chat.title}</p>
1
2
3
4
5
6
2
3
4
5
6
# 后端API
创建文件src/app/api/get-chats/route.ts
import {auth} from "@clerk/nextjs/server";
import {getChats} from "@/db";
export async function POST(req:Request){
const {userId} = await auth()
if (userId){
const chats = await getChats(userId)
return new Response(JSON.stringify(chats),{status:200})
}
return new Response(null, {status:200})
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
测试
405代码是表示返回了API方法不匹配的问题
后端发送了POST请求,前端只支持GET请求
将前端的get改为post
return axios.post(`/api/get-chats`)
1
回到页面
能够查询到历史记录,但显示和高亮有一点问题
需要调整 className
中的 Tailwind CSS 类
将
text-sm
改为text-lg
,使字体大小变大。当前对话框不仅有高亮,还有背景色 'text-blue-700 bg-blue-100'
给p标签加上内边距 p-4
p标签添加圆角效果
效果图 点击不同对话会自动切换路由
文字写于:广东
更新时间: 2025/5/19 01:36:42