zoukankan      html  css  js  c++  java
  • Rewrite JSON project with Fetch

    上传 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));
  • 相关阅读:
    golang IO 流抽象与应用
    postman中 form-data、x-www-form-urlencoded、raw、binary的区别
    golang net/http 包
    MySQL高性能优化系列
    Win10系统中VirtualBox桥接时找不到网卡的问题
    Golang中下划线的使用
    pandas 基础操作 更新
    pandas 基础
    机器学习-树模型理论(GDBT,xgboost,lightBoost,随机森林)
    GBDT 详解分析 转+整理
  • 原文地址:https://www.cnblogs.com/DJOSIMON/p/10167977.html
Copyright © 2011-2022 走看看