【问题标题】:How to send array of object in post request using axios library如何使用 axios 库在 post 请求中发送对象数组
【发布时间】:2020-04-13 06:42:24
【问题描述】:

我需要使用 javascript 对象的数组将数据作为多行插入。

props.email 是一个数组,例如

props.email = [
{email: 'najathi@email.com', name: 'najathi'},
{email: 'naharni@email.com', name: 'naharni'},
]

axios.post('/create-email.php', props.email, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
            .then(response => {
                console.log(response);
            })
            .catch(error => {
                console.log(error);
            });

【问题讨论】:

  • 用户JSON.stringify(),将您的对象数组转换为字符串,然后将数据发送到您的后端。
  • 发生错误.. POST https://../create-email.php 400 错误:请求失败,状态码为 400

标签: javascript reactjs axios


【解决方案1】:

试试,

const payload = {
  email:[
          {email: 'najathi@email.com', name: 'najathi'},
          {email: 'naharni@email.com', name: 'naharni'},
      ]
}

axios.post('/create-email.php', payload, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
})
.then(response => {
    console.log(response.data);
})
.catch(err => {
    console.log(err);
})
    

【讨论】:

  • axios.post() 返回一个响应对象。要从响应中获取数据,您需要编写下一个代码.then(response => { console.log(response.data); })
  • 发生错误.. POST https://../create-email.php 400 错误:请求失败,状态码为 400
  • 尝试为“Content-Type”添加标题。我已经更新了答案。 :)
  • 不支持'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  • 它只支持'Content-Type': 'application/x-www-form-urlencoded'
猜你喜欢
  • 2021-03-16
  • 1970-01-01
  • 2017-09-18
  • 2022-01-18
  • 2019-02-02
  • 1970-01-01
  • 2022-01-21
  • 2019-02-12
  • 1970-01-01
相关资源
最近更新 更多