You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Discord克隆版发送消息时遇Axios 500内部服务器错误求助

Discord克隆应用发送消息触发Axios 500内部服务器错误排查求助

我正在开发一个Discord克隆应用,尝试发送消息时触发Axios 500内部服务器错误,无法定位问题。

请求错误截图1
请求错误截图2

前端ChatInput组件代码(错误触发位置)

const formSchema = z.object({
    content: z.string().min(1),
})

export const ChatInput = ({
    apiUrl,
    query,
    name,
    type
}:ChatInputProps) =>{
    const {onOpen} = useModal();
    const router = useRouter();
    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            content: "",
        }
    });

    const isLoading = form.formState.isSubmitting;

    const onSubmit = async (values: z.infer<typeof formSchema>)=>{
        try {
            const  url = qs.stringifyUrl({
             url: apiUrl,
             query,
            });

            await axios.post(url, values);
            form.reset();
            router.refresh();
        } catch (error) {
            console.log(error, "chat input");
        }
    }
    return(
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)}>
                <FormField 
                 control={form.control}
                 name='content'
                 render={({field})=>(
                    <FormItem>
                        <FormControl>
                            <div className='relative p-4 pb-6'>
                                <button type='button'
                                 onClick={()=> onOpen('messageFile',{apiUrl, query})}
                                 className='absolute top-7 left-8 h-[24px] w-[24px] bg-zinc-500 dark:bg-zinc-400 hover:bg-zinc-600 
                                 dark:hover:bg-zinc-300 transition rounded-full p-1 flex justify-center items-center'
                                >
                                    <Plus className='text-white dark:text-[#313338]' />

                                </button>
                                <Input disabled={isLoading} 
                                 className='px-14 py-6 bg-zinc-200/90 dark:bg-zinc-700/75 border-none
                                 border-0 focus-visible:ring-0 focus-visible:ring-offset-0 text-zinc-600 dark:text-zinc-200'
                                 placeholder={`Message ${type === 'conversation' ? name : '#'+name}`} 
                                 {...field}
                                 />
                                  
                                 <div className='absolute top-7 right-8'>
                                    <EmojiPicker onChange={(emoji:string)=>field.onChange(`${field.value} ${emoji}`)} />
                                 </div>

                            </div>

                        </FormControl>
                    </FormItem>
                 )}
                 />

            </form>
        </Form>
    )
}

后端处理POST请求的API代码

import { currentProfilePages } from "@/lib/current-profile-pages";
import { db } from "@/lib/db";
import { NextApiResponseServerIo } from "@/types";
import { NextApiRequest } from "next";


export default async function handler(
    req: NextApiRequest,
    res: NextApiResponseServerIo,
){
    if(req.method !== 'POST'){
        return res.status(405).json({error: "Method not allowed"})    
    };

    try {
        const profile = await currentProfilePages(req);
        console.log(profile, "jjjjjjjj");
        const {content, fileUrl} = req.body;
        const {serverId, channelId} = req.query;
  
        if (!profile) {
            return res.status(401).json({error: "Unauthorized"});
        }

        if (!serverId) {
            return res.status(400).json({error: "ServerId is missing"});
        }

        if (!channelId) {
            return res.status(400).json({error: "ChannelId is missing"});
        }
    
        if (!content) {
            return res.status(400).json({error: "Content is missing"});
        }

        const server = await db.server.findFirst({
            where: {
                id: serverId as string,
                members:{
                    some:{
                        profileId:profile.id,
                    }
                }
            },
            include: {
                members:true,
            }
        });

        if (!server) {
            return res.status(404).json({message:"server not found"});
        };

        const channel = await db.channel.findFirst({
            where: {
                id:channelId as string,
                serverId:server.id
            }
        });
  
        if (!channel) {
            return res.status(404).json({message:"Channel not found"});
        }
    
        const member = server.members.find((member)=>member.profileId === profile.id);

        if (!member) {
            return res.status(404).json({message:"Member not found"});
        }

        const message = await db.message.create({
            data: {
                content,
                fileUrl,
                channelId: channelId as string,
                memberId: member.id,
            },
            include: {
                member: {
                    include: {
                       profile:true
                    }
                }
            }
        });

        const channelKey = `chat:${channelId}:messages`;
        res?.socket?.server?.io?.emit(channelKey, message);

        console.log(res.json(message))

        return res.status(200).json(message);
    } catch (error) {
       console.log("[Message_Post_Error]", error);
       return res.status(500).json({message:"Internal Error message index"})
    }
}

排查方向

  • 优先看后端具体错误日志:后端catch块里打印了[Message_Post_Error],去服务器控制台找这条日志后面的详细错误信息,这是定位500错误的核心,比如是数据库字段不匹配、认证失败还是其他异常。
  • 检查currentProfilePages函数:这个函数如果抛出异常(比如令牌无效、数据库连接问题),会直接触发500。可以单独测试该函数是否能正常返回用户profile。
  • 数据库字段问题:
    • 前端只传了content,后端却从req.body取fileUrl,如果数据库message表的fileUrl是必填项,创建消息时就会报错。要么给fileUrl设默认值(比如fileUrl: fileUrl ?? null),要么修改表结构允许该字段为空。
    • 确认serverId、channelId的类型和数据库定义一致,比如数据库里是UUID字符串,后端用as string转换是否正确。
  • Socket.io相关:res?.socket?.server?.io?.emit虽然用了可选链,但如果Socket.io未正确挂载到服务器,可能有隐性错误,可以先注释掉这行测试是否还会报错。
  • 请求URL验证:前端用qs.stringifyUrl拼接的URL是否正确?可以在onSubmit里打印url,确认serverId和channelId是否正确出现在查询参数中。
  • 冗余代码影响:后端里console.log(res.json(message))这行多余,res.json()返回的是Promise,而且在return res.status(200).json(message)之前调用,可能影响响应流程,建议注释掉试试。

内容的提问来源于stack exchange,提问作者DarkPhoenixOOO7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 06:57:04