首页 > 其他分享 >fetch请求方式

fetch请求方式

时间:2022-11-23 00:35:22浏览次数:39  
标签:www const 请求 方式 res await json getData fetch

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?id=1&name=jack',{
    method:'post',
    headers:{
      'Content-Type':'applocation/json',  // 这里有多种类型
    },
    // body:请求体,传给请求体的内容切记转成(String)字符串
    body:JSON.stringfiy({name:'jack',phone:'13800138000',address:'灯火阑珊处'})
  })
  const json = await res.json()
  console.log(json)
}

getData()

标签:www,const,请求,方式,res,await,json,getData,fetch
From: https://www.cnblogs.com/melongs/p/16916992.html

相关文章