[英]use axios.patch with a nested JSON
There's a nested JSON object defined in the server side code of the website that I'm working on, like this:在我正在处理的网站的服务器端代码中定义了一个嵌套的 JSON object ,如下所示:
userinfo:{
first_name,
last_name,
profile:{
avatar, //here is the field I need to access!!!
id,
some other properties...
}
}
and I want to upload the avatar picture and as you can see, the avatar property is inside a JS object that is itself inside another JS object,我想上传头像图片,如您所见,头像属性在一个 JS object 中,它本身在另一个 JS object 中,
I'd appreciate it if someone help me with these questions:如果有人帮助我解决这些问题,我将不胜感激:
avatar
property and如何访问avatar
属性和axios.patch()
code to upload the avatar file?我应该如何编写axios.patch()
代码来上传头像文件?dot (.)
notation.要访问 Javascript Object 中的嵌套键,可以使用dot (.)
表示法。 In your case, you can doo something like this在你的情况下,你可以做这样的事情// assuming an object with value
const obj = {
userinfo: {
first_name: 'first name',
last_name: 'last name',
profile:{
avatar: 'https://some-url', //field to be accessed
id: 'xxx-xxx-xxx',
some other properties...
}
}
}
// logging avatar
console.log(obj.userinfo.profile.avatar); // prints "https://some-url"
axios.patch('https://url-endpoint.co', {
avatar: obj.userinfo.profile.avatar
}).then(res => {
// do something on success
console.log(res);
}).catch(err => {
// do something on error
console.log(err);
});
You can read more about axios here - https://github.com/axios/axios#request-method-aliases您可以在此处阅读有关 axios 的更多信息 - https://github.com/axios/axios#request-method-aliases
userinfo.profile.avatar用户信息.profile.avatar
var formData = new FormData();
formData.append('file', userinfo.profile.avatar);
await axios.post('your endpoint url', formData, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
// handle response
console.log(response);
.catch(error => {
// handle error
console.log(error.response);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.