如何使用axios库发送包含对象数组的POST请求

3
我需要使用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()方法,将你的对象数组转换为字符串,然后发送数据到后端。 - Not A Bot
发生错误.. POST https://../create-email.php 400 错误:请求失败,状态码为400。 - Najathi
1个回答

1

Try,

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


1
axios.post() returns a response object. To get data from response you need write the next code .then(response => { console.log(response.data); }) - aopanasenko
发生错误。 POST https://../create-email.php 400 错误:请求失败,状态码为400。 - Najathi
尝试添加“Content-Type”头。我已经更新了答案。 :) - Rahul Sharma
不支持此 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'。 - Najathi
它仅支持 'Content-Type': 'application/x-www-form-urlencoded'。 - Najathi
我已经成功添加了一行数据,但我需要在对象数组中添加多行。 - Najathi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接