美文网首页
react中 fetch 的简单封装

react中 fetch 的简单封装

作者: Luoyilin | 来源:发表于2021-02-24 11:08 被阅读0次
index.js
//get
export function HttpGet(url){
    var result = fetch(url);
    return result
}
// post 
export function HttpPost(url,data){
    var result = fetch(url,{
      headers:{
            'Accept':'application/json,text/plain, */*',
            "Content-Type":"application/x-www-form-urlencoded"
        },
        body:parmas(data)
  })
  return result
}
function parmas(data){
  var results=' ',item;
   for(item in data){
      results+=`&{item} = {encodeURIComponent(data[item])}`
  }
  if(results){
      results=results.slice(1)//去除?
  }
return results
}
http.js
import { HttpGet,Httppost} from './index'
HttpGet('http://www.baidu.com').then(res=>{
  return res.json()
}).then(data=>{
  console.log(data)
})

Httppost('http://www.baidu.com',{
  name:'lili',
  password:'123',
  id:'id123'
}).then(res=>{
  return res.json()
}).then(data=>{
  console.log(data)
})

相关文章

网友评论

      本文标题:react中 fetch 的简单封装

      本文链接:https://www.haomeiwen.com/subject/umajfltx.html