使用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=xxxfrom the frontend fix above), you need to usereq.query.idinstead.req.paramsis for dynamic route segments (e.g.,/api/fetchEditDebt/[id].js). - You're mixing
async/awaitwith callback functions. The callback version offindByIddoesn't return a promise, so yourawaitdoes 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 ofcomponentDidMountto make sure the ID is being passed correctly from the route. - Verify Vercel environment variables: Double-check that your
MONGO_URIis 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 whitelist0.0.0.0/0for testing). - Check form input names: Make sure your input fields have a
nameattribute matching the state keys (e.g.,<input name="provider" ... />), otherwise youronChangehandler won't update the state correctly.
内容的提问来源于stack exchange,提问作者Jon Nicholson
相关产品推荐
相关产品推荐

