fetch封装
1.说明
原生js提供了两种数据请求方式fetch,ajax
- ajax需要封装的, fetch不需要
- fetch也是Promise
2.get请求
//(1)不带参数
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html') // 返回一个Promise对象
.then((res)=>{
return res.text() // res.text()是一个Promise对象
})
.then((res)=>{
console.log(res) // res是最终的结果
})
(2)带参数
methods: {
get () {
fetch(`${ BASE_URL }/get.php?a=1&b=2`)//get请求参数是连接在url上
.then( data => data.text() )
.then( res => {
this.num = res
})
.catch( err => console.log( err ))
},
}
3.post请求
(1)不带参数
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST' // 指定是POST请求
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
(2)带参数
post请求传递参数:
body: new URLSearchParams([["a", 1],["b", 2]]).toString()
注意:POST请求的参数,一定不能放在URL中,这样做的目的是防止信息泄露。
post () {
/*1. post请求参数如何携带*/
fetch(`${ BASE_URL }/post.php`,{
method: 'POST',
// body: JSON.stringify({
// a: 1,
// b: 2
// })
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}),
body: new URLSearchParams([["a", 1],["b", 2]]).toString()
}).then( data => data.text() )
.then( res => {
this.sum = res
})
.catch( err => console.log( err ))
},
例:
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET',
headers: new Headers({
'Accept': 'application/json', // 通过头指定,获取的数据类型是JSON
credentials: 'include' // 强制加入凭据头
})
})
.then((res)=>{
return res.json() // 返回一个Promise,可以解析成JSON
})
.then((res)=>{
console.log(res) // 获取JSON数据
})
fetch的封装:
/**
* 将对象转成 a=1&b=2的形式
* @param obj 对象
*/
function obj2String(obj, arr = [], idx = 0) {
for (let item in obj) {
arr[idx++] = [item, obj[item]]
}
return new URLSearchParams(arr).toString()
}
/**
* 真正的请求
* @param url 请求地址
* @param options 请求参数
* @param method 请求方式
*/
function commonFetcdh(url, options, method = 'GET') {
const searchStr = obj2String(options)
let initObj = {}
if (method === 'GET') { // 如果是GET请求,拼接url
url += '?' + searchStr
method: method,
credentials: 'include'
}
} else {
initObj = {
method: method,
credentials: 'include',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: searchStr
}
}
fetch(url, initObj).then((res) => {
return res.json()
}).then((res) => {
return res
})
}
/**
* GET请求
* @param url 请求地址
* @param options 请求参数
*/
function GET(url, options) {
return commonFetcdh(url, options, 'GET')
}
/**
* POST请求
* @param url 请求地址
* @param options 请求参数
*/
function POST(url, options) {
return commonFetcdh(url, options, 'POST')
}
//使用
GET('https://www.baidu.com/search/error.html', {a:1,b:2})
POST('https://www.baidu.com/search/error.html', {a:1,b:2})
本文作者:丶乔
本文链接:https://www.cnblogs.com/sclweb/p/17637750.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步