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

使用Vercel无服务器函数+Mongoose查询MongoDB填充React表单失败

Let's break down the issues in your code and fix them step by step:

1. Frontend isn't passing the debt ID to your API endpoint

The root cause of your empty form is that your EditDebt component never sends the debt ID from the React Router route to your Vercel API. Right now, your axios call is just hitting /api/fetchEditDebt without any identifying parameter—so the backend can't find the specific document you want, and returns nothing.

Update your componentDidMount method to pass the ID from the route params:

componentDidMount() {
  // Grab the ID from React Router's match params
  const debtId = this.props.match.params.id;
  
  // Pass the ID as a query parameter to your API
  axios.get(`/api/fetchEditDebt?id=${debtId}`)
    .then(response => {
      this.setState({ 
        provider: response.data.provider, 
        balance: response.data.balance, 
        limit: response.data.limit, 
        monthly: response.data.monthly, 
        interest: response.data.interest, 
        borrowed: response.data.borrowed 
      })
      console.log(response.data); // Fix: use 'response' instead of undefined 'res'
      console.log(this.state.provider);
    })
    .catch(error => { 
      console.error("Error fetching debt data:", error);
    })
}

2. Backend API has critical issues

Your Vercel serverless function has two major problems that prevent it from working correctly:

  • You're trying to access req.params.id, but if you're using a query parameter (like ?id=xxx from the frontend fix above), you need to use req.query.id instead. req.params is for dynamic route segments (e.g., /api/fetchEditDebt/[id].js).
  • You're mixing async/await with callback functions. The callback version of findById doesn't return a promise, so your await does nothing, and your response might be sent before the database query finishes.

Rewrite your serverless function to fix these:

const mongoose = require("mongoose");
const SubmitDebt = require("./submitDebtSchema");
require("dotenv").config();

// Reuse the database connection instead of connecting on every request
if (!mongoose.connection.readyState) {
  mongoose.connect(process.env.MONGO_URI);
}

module.exports = async (req, res) => {
  try {
    const id = req.query.id;
    
    // Validate the ID exists
    if (!id) {
      return res.status(400).json({ error: "Debt ID is required" });
    }

    // Use async/await properly for the database query
    const debt = await SubmitDebt.findById(id);
    
    // Handle case where no debt matches the ID
    if (!debt) {
      return res.status(404).json({ error: "Debt not found" });
    }

    console.log("Fetched debt:", debt);
    return res.status(200).json(debt);
  } catch (err) {
    console.error("Database error:", err);
    return res.status(500).json({ error: "Failed to fetch debt data" });
  }
};

3. Additional checks to ensure everything works

  • Confirm React Router params are accessible: Add console.log(this.props.match.params.id) at the start of componentDidMount to make sure the ID is being passed correctly from the route.
  • Verify Vercel environment variables: Double-check that your MONGO_URI is set correctly in your Vercel project settings, and that your MongoDB Atlas (or other provider) allows incoming connections from Vercel's IPs (you can temporarily whitelist 0.0.0.0/0 for testing).
  • Check form input names: Make sure your input fields have a name attribute matching the state keys (e.g., <input name="provider" ... />), otherwise your onChange handler won't update the state correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:12:27