【问题标题】:Why won't an array pass with axios.post?为什么 axios.post 不能通过数组?
【发布时间】:2022-01-10 02:57:40
【问题描述】:

我正在尝试将带有 id 的数组传递到 node.js 中的后端。当 console.log(Products) 在 axios.post() 之前运行时, Products 数组中有两个 id。当我在后端 console.log(req.body.products) 时,数组为空。我怎样才能在我的后端访问数组?

前端代码

const Products = []

                        tempProd.forEach((item) => {
                            firebase.firestore().collection('products').where('name', '==', item.name).get().then((querySnapshot) => {
                                querySnapshot.forEach((doc) => {
                                    Products.push({
                                        price: doc.data().priceID,
                                    })
                                })
                            })
                        })

                        console.log(Products)

                            axios.post('https://Kvam-E-sport-API.olsendaniel04.repl.co/invoice', {
                                products: Products,
                                cus_id: response.data.medlem.id,
                            }).then((response) => {
                                console.log(response)
                            })

后端代码

app.post('/invoice', cors(), async (req, res) => {
      console.log(req.body)
      subscription = await stripe.subscriptions.create({
        collection_method: 'send_invoice',
        customer: req.body.cus_id,
        items: req.body.products,
        days_until_due: 14,
      })

    res.json({
      subscription: subscription
    })
  })

【问题讨论】:

    标签: javascript node.js express axios stripe-payments


    【解决方案1】:

    正在使用正文解析器?例如。

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    

    【讨论】:

    • 是的,我确实使用 bodyparser
    • 您是否尝试过从开发工具中的网络选项卡检查请求?首先查看数据是否发送,如果数据从前端正确发送,那么这是后端问题。
    • 问题已解决。刚刚给axios.post()添加了一个超时时间
    猜你喜欢
    • 2020-04-07
    • 2011-11-19
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2015-11-23
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多