简体   繁体   English

使用带有嵌套 JSON 的 axios.patch

[英]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:如果有人帮助我解决这些问题,我将不胜感激:

  1. how can I access the avatar property and如何访问avatar属性和
  2. how should I write the axios.patch() code to upload the avatar file?我应该如何编写axios.patch()代码来上传头像文件?
  1. To access nested keys inside a Javascript Object, you can use the 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"
  1. Axios Patch is an async function, you can use it like this - Axios 补丁是异步的 function,可以这样使用——
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

  • Answer for number 1, You can get avatar property in:回答数字 1,您可以获得 avatar 属性:

userinfo.profile.avatar用户信息.profile.avatar

  • Answer for number 2, to upload the avatar file use axios you can try this code:回答数字 2,上传头像文件使用 axios 你可以试试这个代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM