【问题标题】:How to pass this.props.match.params.id across to serverless function for database query from React web app如何将 this.props.match.params.id 传递给无服务器函数以从 React Web 应用程序查询数据库
【发布时间】: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


    【解决方案1】:

    这不是发送 get 请求的最佳方式,当发送 get 请求时,参数应该在 url 中发送,现在你正在将 url 连接到一个变量,所以无服务函数它没有获取 id,获取更改如下:

    axios.get("/api/fetchEditDebt",{ params: { id: this.props.match.params.id } })
    
    

    这将等同于 /api/fetchEditDebt?id=sent_id

    所以现在无服务函数获取 params.id:

    module.exports = async (req, res) => {
    
      console.log(req.params.id);
    
      let fetchEditDebts = await SubmitDebt.findById(req.params.id);
      return res.status(200).json(fetchEditDebts);
    
    };
    
    Best regards
    

    【讨论】:

    • 我觉得这很接近......它现在在函数调用中显示 ID,但 ID 仍未定义。我可能需要对我的 React Router 做一些不同的事情吗?我将使用新的错误消息和我的 React Router 代码更新我的问题。
    • 如果你能帮忙,请帮忙。我现在有点绝望,我不知道我做错了什么。
    • 我知道了!!!!不是 req.params,而是 req.query!非常感谢。
    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多