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

调用Next.js API路由出现404(未找到)错误,请求技术排查方案

Next.js API路由404错误分析与解决

核心错误原因

  1. API路由目录不符合Next.js约定
    Next.js的API路由规则是:必须放在src/pages/api(使用src目录结构时)或项目根目录的pages/api下,框架才会自动识别并生成对应的接口。你的api文件夹位于src/views/pages/api,不在框架扫描范围内,因此无法被识别为有效API路由。

  2. Fetch请求路径错误
    即使目录结构正确,你使用的/views/pages/api/save-data也不是Next.js API路由的正确访问路径。框架会将pages/api下的文件映射为/api/[文件名]的接口地址,和其他业务页面目录结构无关。

  3. save-data.ts存在代码逻辑错误

  • saveData函数中insertOne({ order })的order变量未定义,无法正确插入数据;
  • 旧版MongoClient的isConnected()方法已废弃,会导致连接判断逻辑失效。

解决步骤

1. 调整目录结构

将src/views/pages/api目录整体移动到src/pages下,最终结构如下:

src/
  pages/
    api/
      save-data.ts
  views/
    pages/
      wizard/
        checkout/
          Order.tsx

2. 修正Fetch请求路径

修改Order.tsx中的sendDataToServer函数,将请求路径改为/api/save-data:

async function sendDataToServer(data) {
  try {
    const response = await fetch('/api/save-data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (response.ok) {
      const result = await response.json();
      console.log('Data saved:', result);
    } else {
      console.error('Error saving data:', response.status);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

3. 修复save-data.ts的代码错误

import { NextApiRequest, NextApiResponse } from 'next';
import { MongoClient } from 'mongodb';

const uri = "mongodb+srv://xxxx:xxxx@xxxx.xxxxx.mongodb.net/?retryWrites=true&w=majority";

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function saveData(wallet: string, address: string) {
  // 新版本MongoClient的连接状态判断方式
  if (!client.topology || !client.topology.isConnected()) {
    await client.connect();
  }

  const db = client.db('your_database_name');
  const usersCollection = db.collection('users_order');

  // 插入正确的参数
  await usersCollection.insertOne({ wallet, address });
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const { wallet, address } = req.body;

    try {
      await saveData(wallet, address);
      res.status(200).json({ message: 'Data saved successfully' });
    } catch (err) {
      console.error('Error saving data:', err);
      res.status(500).json({ message: 'Error saving data' });
    }
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:42:30