Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • GraphQL
  • Fetch基础用法
    • 基本请求
    • 上传JSON数据
    • 上传文件
  • API 接口设计
HiuZing
2024-01-18
目录

Fetch基础用法

使用 Fetch - Web API 接口参考 | MDN (mozilla.org) (opens new window)

# 基本请求

fetch("http://example.com/movies.json")
  .then((response) => response.json())
  .then((data) => console.log(data));
1
2
3

# 上传JSON数据

const data = { username: "example" };

fetch("https://example.com/profile", {
  method: "POST", // or 'PUT'
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
})
  .then((response) => response.json())
  .then((data) => {
    console.log("Success:", data);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 上传文件

const formData = new FormData();
const 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())
  .then((result) => {
    console.log("Success:", result);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
上次更新: 2024/08/14, 04:14:33
GraphQL

← GraphQL

最近更新
01
React Native 使用SVG
08-13
02
Docker基础命令
08-04
03
算数逻辑单元
07-30
更多文章>
Theme by Vdoing | Copyright © 2021-2024 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式