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

API无响应问题排查及FTP文件下载方式咨询

API无响应问题排查及FTP文件下载方式咨询

看起来你现在遇到了两个核心问题——客户端调用API后没有任何响应日志,同时不确定服务器端的FTP文件下载写法是否正确。我来帮你一步步梳理和修正:

一、客户端无日志的问题

你的客户端代码缺少了错误捕获机制和关键日志输出,而且fetch请求默认不会对非2xx状态码抛出错误,哪怕请求失败你也看不到任何反馈。修改后的代码应该是这样:

useEffect(() => {
  const fetchImagesData = async () => {
    try {
      const response = await fetch("api/galleryData");
      // 先校验响应状态是否正常
      if (!response.ok) {
        throw new Error(`请求失败,状态码:${response.status}`);
      }
      const data = await response.json();
      console.log("获取到的画廊数据:", data); // 打印成功返回的结果
      // 这里可以把数据存入组件状态,比如 setGalleryData(data)
    } catch (error) {
      console.error("请求画廊数据出错:", error); // 捕获并打印所有错误
    }
  };

  fetchImagesData();
}, []);

这样不管请求成功还是失败,你都能在浏览器控制台看到对应的日志,先确认客户端的请求是否真的发送到了服务器,以及服务器返回了什么内容。

二、服务器端FTP下载的写法问题

这是导致客户端收不到响应的核心原因:你当前的Writable流用法完全错误——Node.js的Writable是写流,它不会触发data事件(data事件属于Readable流),而且你没有正确实现_write方法,导致代码大概率卡在await client.downloadTo(...)这一步,服务器永远无法返回响应。

推荐的修正方案:直接下载到Buffer

ftp库提供了更简洁的downloadToBuffer方法,不需要手动处理流,代码会清晰很多:

export async function GET(request: NextRequest) {
  const client = new ftp.Client();
  client.ftp.verbose = true;

  try {
    console.log("Connecting to FTP server...");
    await client.access(ftpConfig);

    const remoteFilePath = "/public_html/images/data/gallery.json";
    console.log(`Downloading file from: ${remoteFilePath}`);

    // 直接下载文件到Buffer,这是最简洁的方式
    const fileBuffer = await client.downloadToBuffer(remoteFilePath);
    const fileContent = fileBuffer.toString("utf8");
    console.log("File content:", fileContent);

    const jsonData = JSON.parse(fileContent);
    console.log("解析后的JSON数据:", jsonData);

    return NextResponse.json({ 
      success: true, 
      data: jsonData, 
      message: "File downloaded successfully." 
    });
  } catch (error) {
    console.error("FTP connection error:", error);
    // 返回具体的错误信息给客户端,方便排查
    return NextResponse.json({ 
      success: false, 
      message: `FTP connection error: ${(error as Error).message}` 
    });
  } finally {
    client.close();
  }
}

如果一定要用流的方式(仅供参考)

如果因为特殊需求必须用流处理,应该使用PassThrough流(它同时实现了Readable和Writable接口)来收集数据:

// 流方式的正确写法(不推荐,Buffer方式更简洁)
import { PassThrough } from "stream";

// ...其他代码不变
const chunks: Uint8Array[] = [];
const passThroughStream = new PassThrough();

passThroughStream.on("data", (chunk) => chunks.push(chunk));

await client.downloadTo(passThroughStream, remoteFilePath);
const fileContent = Buffer.concat(chunks).toString("utf8");
// ...后续处理不变

最后,先修正服务器端的FTP下载逻辑,再用修改后的客户端代码测试,这样就能看到清晰的日志和响应结果了。

备注:内容来源于stack exchange,提问作者david33

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 18:32:58