无心Code

Come on baby!

   ::  :: 新随笔  ::  ::  :: 管理
  7 随笔 :: 1 文章 :: 0 评论 :: 1582 阅读

Fetch请求的方式

1:GET 请求

// 未传参数
const getData = async () => {
const res = await fetch('http://www.xxx.com/data')
const json = await res.json()
console.log(json)
api:
json.ok
}
// 拼接传参
const getData = async () => {
const res = await fetch('http://www.xxx.com/data?id=1&name=jack')
const json = await res.json()
console.log(json)
}
getData()

拼接小技巧

const host = 'http://www.baidu.com'
const json = {name:'longs',age:18,sex:'男',phone:'13800000000'}
const str = new URLSearchParams(json).toString()
const url += '?' + str
console.log(url)
输出:"http://www.baidu.com?name=longs&age=18&sex=%E7%94%B7&phone=13800000000"

2: POST 请求

// 未传请求参数
const getData = async () => {
const res = await fetch('http://www.xxx.com/data',{
method:'post',
headers:{
'Content-Type':'applocation/json', // 这里有多种类型
}
})
const json = await res.json()
console.log(json)
}
// 传入请求参数
const getData = async () => {
const res = await fetch('http://www.xxx.com/data,{
method:'post',
headers:{
'Content-Type':'applocation/json', // 这里有多种类型
'Authorization':localStorage.getItem('token') // 加入token认证 如:'bearer 0d5624ed-b6ed-4ab4-ba46-a6161f0a80bd'
},
// body:请求体,传给请求体的内容切记转成(String)字符串
body:JSON.stringify({name:'jack',phone:'13800138000',address:'灯火阑珊处'})
})
const json = await res.json()
console.log(json)
}
getData()

3: POST 上传文件

const upload = async () => {
const files = ['blob:xxxxx','blob:xxxxxx'] // 数组里面是获取到的二进制文件
const formData = new formData()
const fileArr = []
files.map((item)=> {
fileArr.push(item)
})
formData.append('file',fileArr) //多文件
formData.append('data',JSON.stringify({name:'jack',phone:'13800138000',address:'灯火阑珊处'})) // 额外参数
const res = await fetch('http://www.xxx.com/data,{
method:'post',
headers:{
'Content-Type':'multipart/form-data', // 这里有多种类型
'Authorization':localStorage.getItem('token') // 加入token认证 如:'bearer 0d5624ed-b6ed-4ab4-ba46-a6161f0a80bd'
},
// body:请求体,传给请求体的内容切记转成(String)字符串
body:formData
})
const json = await res.json()
console.log(json)
}
posted on   melong  阅读(118)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示