无心Code

Come on baby!

   ::  :: 新随笔  ::  ::  :: 管理

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 2022-11-23 00:22  melong  阅读(82)  评论(0编辑  收藏  举报