1. 程式人生 > >Rewrite JSON project with Fetch

Rewrite JSON project with Fetch

gif -s data- then photo mozilla content post lec

上傳 JSON 數據

使用fetch()來發布json編碼的數據。

var url = ‘https://example.com/profile‘;
var data = {username: ‘example‘};

fetch(url, {
  method: ‘POST‘, // or ‘PUT‘
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    ‘Content-Type‘: ‘application/json‘
  })
}).then(res => res.json())
.catch(error => console.error(‘Error:‘, error))
.then(response => console.log(‘Success:‘, response));

上傳文件

可以使用HTML<input type="file" />輸入元素、FormData()和fetch()上傳文件。

var formData = new FormData();
var fileField = document.querySelector("input[type=‘file‘]");

formData.append(‘username‘, ‘abc123‘);
formData.append(‘avatar‘, fileField.files[0]);

fetch(‘https://example.com/profile/avatar‘, {
  method: ‘PUT‘,
  body: formData
})
.then(response => response.json())
.catch(error => console.error(‘Error:‘, error))
.then(response => console.log(‘Success:‘, response));

上傳多個文件

可以使用HTML<input type="file" />輸入元素、FormData()和fetch()上傳文件。

var formData = new FormData();
var photos = document.querySelector("input[type=‘file‘][multiple]");

formData.append(‘title‘, ‘My Vegas Vacation‘);
formData.append(‘photos‘, photos.files);

fetch(‘https://example.com/posts‘, {
  method: ‘POST‘,
  body: formData
})
.then(response => response.json())
.then(response => console.log(‘Success:‘, JSON.stringify(response)))
.catch(error => console.error(‘Error:‘, error));

Rewrite JSON project with Fetch