保留上下文对话
# 08.保留上下文对话
这是摘要
# 保存用户信息(后端)
在src/app/api/chat/route.ts
文件中 校验是否已经登录
存入用户信息
我们扩充了参数,需要在前端也添加上新增的参数
useParams()是用于从 URL 中获取参数的钩子
使用useQuery创建一个post请求
# 获取聊天接口
新建src/app/api/get-chat/route.ts
import {unauthorized} from "next/navigation";
import {getChat} from "@/db";
import {auth} from "@clerk/nextjs/server";
export async function POST(req:Request){
const {chat_id} = await req.json()
//判断是否登录,登陆后方可读取
const { userId } = await auth()
if (!userId) {
return new Response(JSON.stringify({error:unauthorized}),{
status: 401,
})
}
//返回chat
const chat = await getChat(chat_id,userId)
return new Response(JSON.stringify({chat}),{status: 200})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
在聊天页src/app/chat/[chat_id]/page.tsx
调用返回的参数
# 获取消息接口
在src/app/chat/[chat_id]/page.tsx
中定义返回消息的前端方法
在后端API中创建src/app/api/get-messages/route.ts
import {getMessagesByChatId} from "@/db";
import {auth} from "@clerk/nextjs/server";
export async function POST(req:Request){
const {chat_id,chat_user_id} = await req.json()
const { userId } = await auth()
//判断是否已登录
if (!userId || chat_user_id !== userId) {
return new Response(JSON.stringify({error:'unauthorized'}),{
status: 401,
})
}
//返回message
const messages = await getMessagesByChatId(chat_id);
return new Response(JSON.stringify({messages}),{status: 200})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
补充page页Message的入参
测试
POST的地址不对
原因在于前端src/app/chat/[chat_id]/page.tsx
的请求路径写的是相对路径
在 /chat/[chat_id]
页面下发起这个请求时
Next.js会基于当前路由路径解析这个相对路径,导致实际请求变成了 /chat/api/get-chat
在请求最开始添加/表示绝对路径(上上张图已更改)
再测试
表示身份验证未通过
创建条件语句,测试一下是哪个问题
是第二个问题
比较两者的输出
是前一个变量没有被定义
找到问题了
后端API实现里返回的数据多用了一个大括号
在 JavaScript 和 TypeScript 中,JSON.stringify
方法用于将一个对象或值转换为 JSON 字符串。在 JSON.stringify
中传递一个对象时,它会将该对象的所有可枚举属性序列化为 JSON 格式。
chat
是一个对象 例子
//没有加{}
{
id: 5,
userId: 'user_2wHxPcxxxxxxxxxxxxxx',
title: '测试保存记录',
model: 'deepseek-v3'
}
//加了{}
{"chat":{"id":"123","userId":"user123","messages":["Hello","World"]}}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
会把结果包裹在一个额外的chat对象中,删去即可
# 测试
退出页面后,对话记录仍有保留
在SupaBase中创建了对话记录
文字写于:广东
更新时间: 2025/4/27 23:24:07