簡體   English   中英

使用帶有嵌套 JSON 的 axios.patch

[英]use axios.patch with a nested JSON

在我正在處理的網站的服務器端代碼中定義了一個嵌套的 JSON object ,如下所示:

userinfo:{
   first_name,
   last_name,
   profile:{
      avatar,    //here is the field I need to access!!!
      id,
      some other properties...
   }
}

我想上傳頭像圖片,如您所見,頭像屬性在一個 JS object 中,它本身在另一個 JS object 中,

如果有人幫助我解決這些問題,我將不勝感激:

  1. 如何訪問avatar屬性和
  2. 我應該如何編寫axios.patch()代碼來上傳頭像文件?
  1. 要訪問 Javascript Object 中的嵌套鍵,可以使用dot (.)表示法。 在你的情況下,你可以做這樣的事情
// 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 補丁是異步的 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);
});

您可以在此處閱讀有關 axios 的更多信息 - https://github.com/axios/axios#request-method-aliases

  • 回答數字 1,您可以獲得 avatar 屬性:

用戶信息.profile.avatar

  • 回答數字 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