req.params not passing from React frontend to serverless function on Axios post request

178 Views Asked by At

I have an edit form which is linked to a serverless function, in which a post request is made based on a Mongoose 'findById'.

The ID is successfully queried when the page is loaded, and the details of the database query are populated on the page.

However, when the post request is submitted, the req.query which was used to find the database entry, is then undefined.

Weirdly, the this.props.match.params.id returns the ID successfully on the client side, but it isn't going through to the serverless function.

Can anyone spot where I'm going wrong?

Here's my code:

Serverless function -

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.");
      });
    }
  });

};

My edit component:

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

I've removed the other functions and inputs from my component to make it more readable.

Any help would be appreciated!

EDIT: I have also tried it as 'req.params.id' instead of 'req.query.id', and unfortunately it says 'id is not defined'. Here's the code and the error message:

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.");
      });
    }
  });

};

And the error message:

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

There are 2 best solutions below

0
On BEST ANSWER

axios.post method is axios.post(url[, data[, config]]). So you should send params object in the third argument.

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

On your react component you are giving the Id as a req.params and on your serverless function you are trying to read from req.query Can you try reading the id from the parameter?

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.");
    }
// ...
});