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

Next.js App Router下API路由无法访问——404 Not Found问题求助

Next.js App Router下API路由无法访问——404 Not Found问题求助

我最近刚接触Next.js,想通过API路由实现发送邮件的功能,但碰到了一个棘手的问题:API路由完全无法访问,一直返回404 Not Found。

先跟大家说下我的项目结构:

  • API路由文件:src/app/api/send-mail/route.ts
  • 调用API的前端组件:src/app/UnityGame.tsx

我甚至手动在浏览器里访问 https://localhost:3000/api/send-mail,结果还是404。我已经反复确认了API路由在正确的目录下,文件里也写好了POST请求处理器,而且确定自己用的是Next.js的App Router,但这个路由就是死活访问不到。

有没有小伙伴遇到过类似的问题?或者能不能帮我分析下可能是什么原因导致的?

附上我的API路由代码:

// src/app/api/send-mail/route.ts
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

export async function POST(req: Request) {
  const { recipient, body } = await req.json();

  if (!recipient || !body) {
    return NextResponse.json({ error: 'Recipient and body are required' }, { status: 400 });
  }

  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: parseInt(process.env.SMTP_PORT || '587'),
    secure: process.env.SMTP_PORT === '465',
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });

  const mailOptions = {
    from: process.env.SMTP_USER,
    to: recipient,
    subject: 'Test Email',
    text: body,
  };

  try {
    await transporter.sendMail(mailOptions);
    return NextResponse.json({ message: 'Email sent successfully' });
  } catch (error) {
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

另外,我从客户端组件发送请求到这个API端点时,也完全连不上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:10:29