【问题标题】:How to POST an array to axios如何将数组发布到 axios
【发布时间】:2020-12-15 18:11:20
【问题描述】:

我有以下代码

const onSubmit = data => {

    let params = {
        experience_type: data.education[0].type,
        body: data.education[0].text,
        start_time: data.education[0].from,
        end_time: data.education[0].to,
        
    }

    axios.post('http://localhost:5000/experience', params)
        .then((response) => {
            console.log(response);

        }, (error) => {
            console.log(error);
        });



  
};

我想使用 Axios 发布整个 data.education 数组。目前我只能发布第一个索引。我将如何使用 axios 发布 data.education 数组的所有索引。我目前的想法是使用扩展运算符并单独传递每个运算符。

【问题讨论】:

  • 嘿..你能分享你的数据库模型代码吗
  • 请 console.log(data) 分享结果

标签: node.js reactjs post axios


【解决方案1】:

您可以使用JSON.stringify(data.education) 一次传递整个数据数组。但是您需要在后端适当地处理集合。

【讨论】:

  • 感谢您的回答。我有一个在后端运行的 postgresql 数据库,我想将它逐行插入。我希望 axios 有一种方法可以批量请求,或者我可以使用扩展运算符单独发送它们。
  • 您可以为此目的使用FormData。查看此帖子:stackoverflow.com/a/58056214/9971139
【解决方案2】:

答案是将整个对象发送到快速路由,然后映射对象,一次将每一行插入数据库。因此,一个 Axios 发布请求并按照其他人指出的那样处理路由中的其余部分。

 req.body.education.forEach(async values => {



        const newPost = await pool.query(`INSERT INTO Experience (experience_type, start_time, end_time, user_id, author,body,date_created) 
        VALUES($1,$2,$3,$4,$5,$6, NOW()) RETURNING * `,
            [values.experience_type, values.start_time, values.end_time, USER ID HERE, USERNAME HERE, values.body]);

        res.json(newPost[0]);

这是对象被映射然后插入到各个行中的方式

【讨论】:

    【解决方案3】:

    这将帮助你亲爱的伙伴。

        var axios = require('axios');
        var qs = require('qs');
        var data = qs.stringify({
         'experience_type': data.education[0].type,
         'body': data.education[0].text,
         'start_time': data.education[0].from,
         'end_time': data.education[0].to,
        });
        var config = {
           method: 'post',
           url: 'http://localhost:5000/experience',
           headers: { 
             'Content-Type': 'application/x-www-form-urlencoded'
           },
           data : data
        };
    
        axios(config)
         .then(function (response) {
             console.log(JSON.stringify(response.data));
         })
         .catch(function (error) {
             console.log(error);
         });
    

    【讨论】:

    • 感谢您的回答。但是,这不仅适用于数组中的第一个索引吗?发送整个对象然后对其进行迭代不是更容易吗?
    • 是的,您可以发送完整的对象并在后端对其进行迭代。我只是根据你的问题调整它。干杯!
    猜你喜欢
    • 2021-11-13
    • 2023-03-26
    • 2021-12-14
    • 2023-03-15
    • 2021-11-15
    • 2019-04-12
    • 2021-11-23
    • 2017-08-04
    • 2022-01-25
    相关资源
    最近更新 更多