0

I have a post request being handled on my backend with express and node.js

When this post request comes in console.log(amount) is showing undefined, then 1/2 second later it reads the amount correctly.

My issue is that my route is firing off the stripe.charges.create function before the amount has time to load.

Is there a way to somehow stall this process until req.body is fully loaded?

Here is my controller function

app.post('/api/stripe', async (req, res) => {
  const { amount } = req.body
  console.log(amount)
  const charge = await stripe.charges.create({ // <-- this is firing before amount has time to load
    amount: req.body.amount,
    currency: 'usd',           
    description: 'Credit purchase',
    source: req.body.id
  })
  console.log(req.body.amount) // < same as const { amount } = req.body
  console.log(charge) 
});

I am dispatching these two functions from the front end

export const handleAmount = (amount) => async () => {
  try {
    const { data } = await axios({
      url: "http://localhost:5000/api/stripe",
      method: "POST",
      data: {
        amount: amount
      },
      withCredentials: true
    }).then()
  } catch (error) {
    console.log(error)
  }
}

this is the second function being dispatched. These 2 functions are dispatched at the same time in the same function

 // sending stripe token to backend
 export const handleToken = (token) => async dispatch => {
   const res = await axios.post('http://localhost:5000/api/stripe', token);
   dispatch({
     type: FETCH_USER,
     payload: res.data
   });
 };

this is what my console.log looks like

enter image description here

Phil
  • 157,677
  • 23
  • 242
  • 245
AmandaConda
  • 223
  • 3
  • 13
  • This doesn't seem right. The route handler will not be entered until the request is finalised. Any request body parameters should be complete unless you've got some middleware doing something with it asynchronously. What middleware have you registered (eg `express.json()`, `express.urlencoded()`, etc)? What does the request from the client-side look like? – Phil Aug 04 '21 at 02:11
  • _"1/2 second later it reads the amount correctly."_... what does this mean? Where are you validating this? There is nothing in the code shown that waits for 500ms – Phil Aug 04 '21 at 02:15
  • Looks to me like you're receiving 4 different requests where the latter 2 have an `amount` property in the request body – Phil Aug 04 '21 at 02:23
  • Are you sure your `handleToken` function is using the correct URL? It's the same one as `handleAmount` – Phil Aug 04 '21 at 02:25
  • Use middleware to process the incoming body. Like `app.use(express.json())`. [More info](https://stackoverflow.com/a/51844327/1563833) – Wyck Aug 04 '21 at 02:29
  • I was actually just wondering about that... Thanks I will have answer shortly – AmandaConda Aug 04 '21 at 02:31
  • Still couldnt figure it out.... – AmandaConda Aug 04 '21 at 07:14

0 Answers0