首页 > 解决方案 > 如何让发布请求等到 req.body.value 在运行下一个函数之前加载

问题描述

我在后端使用 express 和 node.js 处理了一个发布请求

当此发布请求进入时,console.log(amount) 显示未定义,然后 1/2 秒后它会正确读取金额。

我的问题是我的路线在金额有时间加载之前触发了 stripe.charges.create 函数。

有没有办法以某种方式停止这个过程,直到 req.body 完全加载?

这是我的控制器功能

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

我从前端调度这两个函数

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)
  }
}

这是第二个被调度的函数。这2个函数在同一个函数中同时调度

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

这就是我的 console.log 的样子

在此处输入图像描述

标签: node.jsexpress

解决方案


推荐阅读