接口请求

接口请求

GET POST PUT PATCH DELETE

AJAX(Asynchronous JavaScript and XML)

其他:ajax基本使用

前言

POST请求的请求体格式

使用代码时在content-type中指定,使用接口工具,选中POST时也有对应的类型选择

none

不传递请求体,类似于get请求。通常会用于资源获取,状态查询之类

application/x-www-form-urlencoded

数据以键值对的形式,就像是URL参数一样,特殊字符也会被转义,比如空格会转义为+或者%20(不同标准中,但都能被识别)

1
name=zs&age=20
  • 适用于简单的表单提交

application/json

数据以json对象的形式

1
2
3
4
{
"name": "zs",
"age": 20
}
  • 自由的数据格式

application/octet-stream

直接发送二进制数据,对于图片这种还有image/jpegimage/png

  • 适用于文件上传

multipart/form-data

支持上传文件和二进制数据,同时也可以包含文本字段。请求体会被分为多个部分,每个部分都有自己的Content-Type

1
2
3
4
5
6
7
8
9
10
11
Content-Type: multipart/form-data; boundary=---------------------------1234567890

-----------------------------1234567890
Content-Disposition: form-data; name="username"

john
-----------------------------1234567890
Content-Disposition: form-data; name="avatar"; filename="photo.jpg"
Content-Type: image/jpeg

[二进制数据...]
  • 适用于上传文件、含文本和文件的表单提交

原生

XMLHttpRequest

最早的ajax实现

1
2
3
4
5
6
const xhr = new XMLHttpRequest();
xhr.open("get", "http:localhost/test");
xhr.send();
xhr.onload = function () {
console.log(xhr.responseText);
};

fetch

现代ajax的实现,现代浏览器提供的 Promise-based API。支持更多HTTP功能,如请求头设置、超时设置、请求取消等等等等等

链式调用

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

async/await

1
2
3
4
5
6
7
8
9
10
11
async function fetchData() {
const response = await fetch("http://example.com/movies.json", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
}

fetchData();

为什么要response.json()

fetch返回的是一个Response对象,Response对象中包含了如状态码、状态信息、响应头、响应体等信息,这个方法是将响应对象转换为json对象

流式数据处理(如大文件下载),边接收边处理

1
2
3
4
5
fetch('https://api.example.com/large-file')
.then(response => {
const reader = response.body.getReader();
// 处理流数据...
});

axios

基于Promise,浏览器端基于XHR,node端基于node内置http模块。

优势在于拦截器、自动转换JSON数据(fetch需要res.json())、内置上传进度、取消请求等

请求拦截

1
2
3
4
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
});

响应拦截

1
2
3
4
5
6
7
8
9
10
axios.interceptors.response.use(
response => response.data,
error => {
if (error.response.status === 401) {
// 自动处理登录过期
logout();
}
return Promise.reject(error);
}
);

请求取消(CancelToken),比原生的fetch取消更加早,axios在2014年支持请求取消,fetch在2017年支持

1
2
3
4
5
6
7
const source = axios.CancelToken.source();

// 发送请求并传入 cancelToken
axios.get('/api/data', { cancelToken: source.token });

// 取消请求(参数是可选的取消消息)
source.cancel('请求已取消');

请求取消(AbortController),向fetch原生靠拢

1
2
3
4
5
6
7
8
9
10
const controller = new AbortController();
const signal = controller.signal;

axios.get('/api/data', { signal })
.then(response => {})
.catch(error => {});

controller.abort();

fetch('/api/data', { signal })

got

主要支持node环境,原生支持.stream(),axios需要responseType: 'stream'

直接返回可读流

1
got.stream('https://example.com/file.zip').pipe(fs.createWriteStream('file.zip'));

简约的链式调用

1
2
3
4
// 带查询参数和超时的请求
await got('https://api.example.com')
.searchParams({ page: 1, limit: 10 })
.timeout(5000);
作者

dsjerry

发布于

2025-06-25

更新于

2025-06-26

许可协议

评论