我有一个函数,我使用axios将数据发布到nodeJS rest api。我遇到的问题是axios添加了一个带有对象的列表,而不仅仅是数组对象。请帮我解决这个问题
函数从"documents">
中接收以下内容{
_id: '6149290b197615d32c515dab',
instantMessage: false,
isComplete: true,
},
{
_id: '614a249636503d7aa9fb138d',
instantMessage: false,
isComplete: true,
},
{
_id: '614a2bf5560184026def253a',
date: '2021-09-21',
title: 'Not getting erro',
},
{
_id: '614a2c6a560184026def253d',
date: '2021-09-21',
title: 'Every thing working',
}
我的功能如下:
async function SaveAsTemplate(documents) {
const result = await axios
.post('http:localhost/templates', {
documents,
})
.catch(function (error) {
// handle error
console.warn(error.message);
});
return result;
}
在收到查询的nodeJS项目中,我是console.log数据,我得到以下结果:
documents: [
{
_id: '6149290b197615d32c515dab',
instantMessage: false,
isComplete: true,
},
{
_id: '614a249636503d7aa9fb138d',
instantMessage: false,
isComplete: true,
},
{
_id: '614a2bf5560184026def253a',
date: '2021-09-21',
title: 'Not getting erro',
},
{
_id: '614a2c6a560184026def253d',
date: '2021-09-21',
title: 'Every thing working',
}
]
我如何使用axios,它只给我对象而不给前面的文档。当我使用邮差和其他工具发送查询帖子时,我没有这个问题,一切都是正确的。只有在使用axios
时才有问题你在做
const result = await axios
.post('http:localhost/templates', {
documents,
})
等于:
const result = await axios
.post('http:localhost/templates', {
documents: documents,
})
试题:
const result = await axios
.post('http:localhost/templates', documents)
async function SaveAsTemplate(documents) {
const result = await axios
.post('http:localhost/templates', {
headers: {
'Content-Type': 'application/json',
},
body: documents,
})
.catch(function (error) {
// handle error
console.warn(error.message);
});
return result;
}
或者你可以尝试先将array改为object然后再赋值body post