req.params没有从React前端传递到Axios发布请求上的无服务器功能

时间:2020-10-24 09:05:06

标签: reactjs serverless vercel

我有一个链接到无服务器功能的编辑表单,其中基于Mongoose'findById'发出发布请求。

页面加载后成功查询到ID,并在页面上填充数据库查询的详细信息。

但是,提交提交请求时,用于查找数据库条目的req.query则未定义。

奇怪的是,this.props.match.params.id在客户端成功返回了ID,但是没有传递给无服务器功能。

有人能发现我要去哪里错吗?

这是我的代码:

无服务器功能-

module.exports = async (req, res) => {


  await SubmitDebt.findById(req.query.id, function(err, submitdebt) {
    if (!submitdebt) {
      console.log(req.query.id);
      res.status(404).send("Unable to find entry to edit.");
    }
    else {
      console.log(req.query.id);
      submitdebt.creditCard = req.body.creditCard;
      submitdebt.personalLoan = req.body.personalLoan;
      submitdebt.provider = req.body.provider;
      submitdebt.balance = req.body.balance;
      submitdebt.limit = req.body.limit;
      submitdebt.monthly = req.body.monthly;
      submitdebt.interest = req.body.interest;
      submitdebt.borrowed = req.body.borrowed;

      submitdebt.save().then(submitdebt => {
        res.json("Debt successfully updated.");
      })
      .catch(err => {
        res.status(400).send("Debt unsuccessfully updated.");
      });
    }
  });

};

我的编辑组件:

class EditDebt extends Component {
  constructor(props) {
    super(props)

    this.state = {

      balance: ''

    }

    this.onChange = this.onChange.bind(this);
  }



  onChange = (e) => {
        this.setState({ [e.target.name]: e.target.value})
    }

  onSubmit = async (e) => {

      e.preventDefault();

      console.log(this.props.match.params.id)

      await axios.post("/api/editDebtCard", { params: { id: this.props.match.params.id } }, {

        balance: this.state.balance

      })

      this.props.history.push('/dashboard');
    }

  render() {

    return (

      <section className="edit-debt-section">

      <div className="edit-debt-container">

      <form className="edit-debt-form" method="POST" onSubmit={this.onSubmit}>
        <div className="edit-debt-form-container">

          <label className="edit-debt-label">What's the balance?</label>
            <div className="edit-debt-input-container">
              <h6 className="edit-debt-input-text">£</h6>
              <input className="edit-debt-number-input" type="number" name="balance" value={this.state.balance} onChange={this.onChange} step="0.01" />
            </div>



          <button className="edit-debt-update-button" type="submit" name="button">Create</button>

          </div>
          </form>
      </div>

    </section>
    )

  }
}

export default EditDebt

我从组件中删除了其他功能和输入,以使其更具可读性。

任何帮助将不胜感激!

编辑:我也尝试过将它作为'req.params.id'而不是'req.query.id',但不幸的是它说'id is not defined'。这是代码和错误消息:

module.exports = async (req, res) => {


  await SubmitDebt.findById(req.params.id, function(err, submitdebt) {
    if (!submitdebt) {
      console.log(req.params.id);
      res.status(404).send("Unable to find entry to edit.");
    }
    else {
      console.log(req.params.id);
      submitdebt.balance = req.body.balance;

      submitdebt.save().then(submitdebt => {
        res.json("Debt successfully updated.");
      })
      .catch(err => {
        res.status(400).send("Debt unsuccessfully updated.");
      });
    }
  });

};

错误消息:

2020-10-24T12:05:51.806Z    279ac48e-af0b-49d1-bd13-4056f765ec40    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/editDebtCard.js:22:40)","    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

2 个答案:

答案 0 :(得分:1)

axios.post方法是axios.post(url[, data[, config]])。因此,您应该在第三个参数中发送params对象。

await axios.post("/api/editDebtCard",
  {
    balance: this.state.balance
  },
  {
    params: {
      id: this.props.match.params.id
    }
  }
)

答案 1 :(得分:0)

在您的react组件上,您将ID设为req.params,在您的无服务器功能上,您试图从req.query进行读取?您可以尝试从参数中读取ID吗?

await SubmitDebt.findById(req.params.id, function(err, submitdebt) {
    if (!submitdebt) {
      console.log(req.params.id);
      res.status(404).send("Unable to find entry to edit.");
    }
// ...
});