【发布时间】:2020-10-23 23:53:49
【问题描述】:
我有一个 React 前端,带有一个 Axios GET 调用。在这个 get 调用中,我试图在最后传递 'this.props.match.params.id'。
有了这个“this.props.match.params.id”,我试图在我的无服务器函数上使用它来使用“findById”函数查询我的 MongoDB 数据库。
但是,每当我将“this.props.match.params.id”添加到末尾(如下所示)时,该函数都不会触发。如果我删除它,函数会触发,但返回 undefined。
如果我改为尝试“req.params.id”,它会返回“id 未定义”的错误。
供参考 - 当我单击“编辑”链接以提取 ID 时,URL 成功更新。如果我还控制台“this.props.match.params.id”,它会在我的 Axios 调用中返回正确的 ID .
如何将“this.props.match.params.id”传递给我的无服务器函数,并使用它通过“findById”查询我的数据库?
这是我的代码:
我的无服务器函数
module.exports = async (req, res) => {
console.log(req.params);
let fetchEditDebts = await SubmitDebt.findById(req.params);
return res.status(200).json(fetchEditDebts);
};
我的 Axios 在 React 代码中被调用 with this.props.match.params.id:
componentDidMount() {
axios.get("/api/fetchEditDebt", { params: { id: this.props.match.params.id } })
.then((response) => {
console.log(response)
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
})
}
而我的 Axios 调用 没有 this.props.match.params.id:
componentDidMount() {
axios.get("/api/fetchEditDebt")
.then((response) => {
console.log(response)
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
})
}
任何提示/提示将不胜感激。如果您需要更多详细信息,请告诉我。
编辑:我尝试了下面的答案(并编辑了我的代码以反映..但现在收到一条错误消息'id not defined'。如下:
2020-10-23T15:51:44.222Z 39718d37-7a13-4240-a01c-90030916edf8 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read property 'id' of undefined","reason":{"errorType":"TypeError","errorMessage":"Cannot read property 'id' of undefined","stack":["TypeError: Cannot read property 'id' of undefined"," at module.exports (/var/task/api/fetchEditDebt.js:12:28)"," at Server.<anonymous> (/var/task/___now_helpers.js:813:19)"," at Server.emit (events.js:315:20)"," at parserOnIncoming (_http_server.js:790:12)"," at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: Cannot read property 'id' of undefined"," at process.<anonymous> (/var/runtime/index.js:35:15)"," at process.emit (events.js:327:22)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
Unknown application error occurred
我使用 React Router 的路由:
import EditDebt from './components/edit-debt/edit-debt';
function App() {
return (
<Switch>
<Route path="/edit/:id" component={EditDebt} />
</Switch>
【问题讨论】:
标签: reactjs mongoose serverless vercel