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

Next.js如何访问非public目录文件?API路由报错求助

Next.js 访问项目根目录下图片文件的问题解决

错误原因

你使用的NextResponse.send()是Next.js Pages Router专属的API,而当前你基于App Router(通过route.js定义路由)开发,该方法在App Router中不存在,因此触发报错。

解决方案一:修正API路由代码

改用new Response返回图片二进制数据,并配置正确的响应头:

import fs from 'fs';
import path from 'path';
import { NextResponse } from 'next/server';

export async function GET(req) {
  const { searchParams } = new URL(req.url);
  const id = searchParams.get("id");
  
  if (!id) {
    return NextResponse.json({ error: '缺少id参数' }, { status: 400 });
  }

  const imagePath = path.join(process.cwd(), 'uploads', 'qr', `${id}.png`);

  try {
    const imageBuffer = fs.readFileSync(imagePath);
    return new Response(imageBuffer, {
      headers: {
        'Content-Type': 'image/png',
      },
    });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: '图片不存在' }, { status: 404 });
  }
}

解决方案二:利用静态文件服务(更高效)

Next.js默认仅对外提供public目录下的静态文件访问权限,可将uploads目录迁移至public目录下,目录结构变为:

public/
  uploads/
    qr/
      myimage.png

之后直接通过URL即可访问:http://localhost:3000/uploads/qr/myimage.png,无需编写API路由。

提示:若图片为动态生成、无法提前放入public目录,选择方案一;若为静态文件,方案二更节省服务器资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:09:59