首先,
fetch
是一种现代的网络请求API,用于在浏览器
或 Node.js
环境中` 发送 HTTP 请求,
它是 XMLHttpRequest 和 Ajax 的现代替代品,提供了更简洁、更强大的功能。
说一下下面的共同点
首先,请注意,
每个`.then()`方法后面的函数都处理`fetch请求`的不同阶段:
`第一个.then()`,用于处理响应状态,并决定是继续解析响应体还是抛出错误,
`后续的.then()`,用于处理解析后的响应数据,
`.catch()`,用于捕获在请求过程中的任何错误。
发送GET请求
fetch('https://api.example.com/items', {
method: 'GET', // 默认就是 GET,可以省略
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token-here'
}
})
.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('There has been a problem with your fetch operation:', error)
})
发送POST请求,包含FormData
const formData = new FormData()
formData.append('file', fileInput.files[0])
formData.append('username', 'johndoe')
fetch('https://api.example.com/upload', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.text(); // 根据后端返回的内容类型选择解析方法
})
.then(result => {
console.log('Upload successful:', result)
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error)
})
发送POST请求,包含JSON数据
const data = { name: 'John Doe', age: 30 }
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})
.then(result => {
console.log('Success:', result)
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error)
})
发送带有自定义参数的 GET 请求
const params = {
page: 1,
per_page: 10
}
const urlWithParams = new URL('https://api.example.com/items')
Object.keys(params).forEach(key => urlWithParams.searchParams.append(key, params[key]))
fetch(urlWithParams, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.error('Error:', error)
})
这里使用了"URLSearchParams"来创建带有查询参数的"URL字符串",
这种方式,比手动拼接URL字符串,更安全,
因为,它会自动处理特殊字符的编码问题。