Javascript Vue使用axios发送base64,但为空
我有一个表单,我需要发送几个图像,所以我在一个Base64中变换每个图像,正如您在下面看到的,对象存在,但是当我从开发工具访问网络时,对象是空的!有人知道为什么会这样? 在vue中发布方法Javascript Vue使用axios发送base64,但为空,javascript,vue.js,post,base64,axios,Javascript,Vue.js,Post,Base64,Axios,我有一个表单,我需要发送几个图像,所以我在一个Base64中变换每个图像,正如您在下面看到的,对象存在,但是当我从开发工具访问网络时,对象是空的!有人知道为什么会这样? 在vue中发布方法 this.topografiaItems.forEach(function(topografia) { topografia.anexos.forEach(function(anexo, index) { let rea
this.topografiaItems.forEach(function(topografia) {
topografia.anexos.forEach(function(anexo, index) {
let reader = new FileReader();
reader.readAsDataURL(anexo);
reader.onloadend = function () {
topografia.anexos[index] = reader.result;
};
reader.onerror = function () {
console.log('Error', error);
};
});
});
console.log(this.topografiaItems);
axios.post(this.path, this.topografiaItems,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then( (response) => {
console.log(response);
});
reader.readAsDataURL(anexo)代码>是异步的。forEach
循环是同步的。axios.post
在实际加载数据之前发生。
一种解决方案是使用承诺包装器并等待
类似于的东西非常感谢!首先,你的回答有助于解决以下问题。正如您所说,Reader类是异步的,因此我必须将我的函数封装在一个承诺中,以解决顶级问题。另一个问题是我是在循环中这样做的,我不能更改引用的值,这会导致我找到一个循环解决方案(),但它可以完美地工作。如果有人有更好的实现,请分享!感谢如果您在中使用了let
而不是const
for您正在使用的
迭代器,您应该能够更改。没有“最佳”解决方案。有些人喜欢突变,有些人不喜欢。对于非变异,最好从这个迭代中获得一个新数组,然后在您的帖子中再次使用它,谢谢!我不注意康斯特。改变这一切都是完美的。钢笔更新