前端网络请求有很多种方法,各个请求方法的用法、参数等等非常记混,本文讲按类别带着大家梳理前端网络世界中的请求方法。
XHLHttpRequest(XHR)
XMLHttpRequest
是执行异步请求的传统方式,也是前端最先出现请求方法。XHR可以实现从服务器获取数据并且无感刷新(不重新加载页面)。
示例
const xhr = new XMLHttpRequest()
xhr.open("GET", "https://api.example.com/data", true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
xhr.send()
由于现在并不常用,我们就不细讲。
Axios
Axios 是一个基于 Promise
的HTTP客户端,适用于浏览器和node.js
。Axios提供了许多便捷的功能,比如他会自动转换JSON数据。
GET请求
多用于请求服务器的某个数据
axios.get('/user?ID=mcell')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
// 或者
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
// 对于异步的支持
async function getUser() {
try {
const response = await axios.get('/user?ID=mcell');
console.log(response)
} catch (error) {
console.error(error)
}
POST请求
POST
请求用于向服务器提交要被处理的数据。比如文件上传、登录或者注册用户信息。
axios.post('/user', {
firstName: 'm',
lastName: 'cell'
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
PUT请求
PUT多用于更新全部资源或者部分资源
axios.put('/user/mcell', {
name: 'M',
age: 20
})
.then(function (res) {
console.log(res)
})
.catch(function (err) {
console.log(err)
})
DELETE请求
和他的名字一样,DELETE请求多用于删除指定资源
axios.delete('/user/mcell')
.then(function (res) {
console.log(res)
})
.catch(function (err) {
console.log(err)
})
PATCH 请求
patch请求多用于对资源进行部分更新。
axios.patch('/user/mcell', {
name: 'minorcell'
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
HEAD请求
用于获取资源的元数据(例如,是否存在、资源类型等),而不传输资源本身。
axios.head('/user/mcell')
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
OPTIONS 请求
用于获取目的资源所支持的通信选项。
一个OPTIONS请求到服务器之后,可以查询服务器支持的HTTP方法(如GET、POST、DELETE等)。
axios.options('/user/mcell')
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
POST和GET请求区别
POST和GET请求是非常容易混淆的,比如使用场景区别和参数区别等等
使用场景区别
- GET请求主要用于请求数据。多用于从指定的资源请求数据,通常不会导致服务器上的状态变化。因此,GET请求应该是安全且幂等的,换句话说多次发出同样的GET请求,其效果应该与一次请求相同。
- POST请求通常用于提交数据。多用于向指定的资源提交要被处理的数据,例如,提交表单数据。POST请求可能会导致服务器上的状态变化或资源的创建。
参数传递区别
- GET请求的参数通常附加在 URL 之后,以
?
分隔URL和传递的参数,参数之间用&
连接。由于URL的长度限制,GET请求能发送的数据量有限。 - POST请求的数据则放在 HTTP请求 的消息体(body) 中发送,因此可以传输更多的数据,理论上没有大小限制。
FETCH
fetch
是现代JavaScript提供的一个功能强大且灵活的网络请求API,同XHR一样,可以在JS代码中直接使用。对比XHR,使用方法上更简洁、也是基于PROMISE。在用法上和AXIOS很相像。
基本用法
fetch
的基本用法是调用fetch()
函数,并传入所需资源的URL。返回一个Promise
,该Promise
在请求成功时解析为一个Response
对象。
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})
.then(data => console.log(data)) // 处理数据
.catch(error => console.error('Fetch error:', error)) // 错误处理
对于JSON的处理
Response
对象提供了一个.json()
方法,可以返回一个Promise。
fetch('https://api.example.com/data')
.then(response => response.json()) // 直接解析JSON
.then(data => console.log(data));
FETCH提供的方法
.json
: 解析响应体为 JSON 对象
.text()
:将响应体作为文本返回.formData()
:解析响应体并将其作为FormData
对象返回。.blob()
:将响应体解析为Blob
对象。适用于处理二进制数据,如图像或文件。