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

Next.js API无响应报错+Sanity视频上传异步问题求助

问题分析与解决思路

核心问题

你的代码存在两个关键问题导致报错:

  • API路由的POST分支未正确等待Promise完成,也没有异常处理逻辑,导致Next.js判定请求未返回响应,触发"API resolved without sending a response"错误
  • 未捕获client.create和前端请求的异常,引发未处理的ClientError

第一步:修复API路由(api/post/index.ts)

原POST分支用.then()但未使用await,函数会提前结束;同时缺少错误捕获,导致异常无法处理。改成await+try/catch确保响应正确发送,同时捕获异常:

import type { NextApiRequest, NextApiResponse } from 'next';
import { allPostsQuery } from '../../../utils/queries'; 
import { client } from '../../../utils/client';

export default async function handler(req: NextApiRequest, res: NextApiResponse) { 
  if (req.method === 'GET') { 
    const query = allPostsQuery();
    const data = await client.fetch(query);
    res.status(200).json(data);
  } 
  else if (req.method === 'POST') {
    try {
      const doc = req.body;
      // 用await等待create操作完成
      await client.create(doc);
      res.status(201).json('video created');
    } catch (error) {
      // 捕获Sanity的ClientError并返回错误响应
      console.error('创建文档失败:', error);
      res.status(500).json({ 
        error: '创建视频帖子失败', 
        details: error instanceof Error ? error.message : '未知错误' 
      });
    }
  }  
  // 处理其他不支持的请求方法
  else {
    res.setHeader('Allow', ['GET', 'POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

第二步:修复前端handlePost函数

前端需要捕获axios请求的异常,同时确保setSavingPost在失败时能重置状态,避免一直显示"保存中":

const handlePost = async () => { 
  if (!caption || !videoAsset?._id || !topic) return;

  setSavingPost(true);    
  const doc = {
    _type: 'post',
    caption,
    video: {
      _type: 'file',
      asset: {
        _type: 'reference',
        _ref: videoAsset._id,
      },
    },
    userId: userProfile?._id,
    postedBy: {
      _type: 'postedBy',
      _ref: userProfile._id,
    },
    topic,
  };

  try {
    await axios.post('http://localhost:3000/api/post', doc);
    router.push("/");
  } catch (error) {
    console.error('提交帖子失败:', error);
    // 这里可以添加用户友好提示,比如弹窗或Toast
    alert('保存帖子失败,请稍后重试');
  } finally {
    // 无论成功失败,都重置保存状态
    setSavingPost(false);
  }
};

额外排查点

  1. 确认Sanity的client配置正确,服务端路由需使用具备写入权限的服务端token
  2. 检查videoAsset._id是否是Sanity中已存在的文件资源ID,避免引用不存在的资源导致Mutation失败
  3. 核对Sanity的post类型schema定义,确保和你提交的doc结构完全匹配(比如postedBy是否为引用类型、video是否为文件引用类型)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:22:50