1、request库
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44//导入axios import axios from 'axios'; //设计为一个方法调用,method默认值为“get“,data为数据,config为上传图片时的加载进度 export function request(url,method="get",data={},config={}) { return axiosRequest(url, method, data,config); } function axiosRequest(url,method,data,config){ //接收后改为小写 if (method.toLocaleLowerCase()==="post"){ //设一个key-value接收格式,然后遍历出来 let params=new URLSearchParams(); if (data instanceof Object){ for (let key in data){ params.append(key,data[key]); } data = params; } //当接收的method为上传文件时,将其设为post,并将文件的key-value加入data数据流。 }else if (method.toLocaleLowerCase()==="file"){ method="post"; let params=new FormData(); if (data instanceof Object){ for (let key in data){ params.append(key,data[key]); } data = params; } } //将参数都放在axiosConfig变量里面。 let axiosConfig={ method:method.toLocaleLowerCase(), url:url, data:data, }; //将上传文件的进度加入data数据流 if (config instanceof Object){ for (let key in config){ axiosConfig[key]=config[key]; } } //直接调用请求然后返回即可 return axios(axiosConfig).then(res=>res.data); }
2、上传图片的demo
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41import React from 'react'; import {request} from '../js/request'; //上传图片 uploadHead(e){ // console.log(e.target.files[0]);此方法不用写ref // console.log(this.refs["head-file"].files[0]) let headFile=e.target.files[0]; // let data=new FormData(); // data.append("headfile",headFile); //上传进度展示percentVal var config = { onUploadProgress: (progressEvent)=> { var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); console.log(percentCompleted); this.setState({percentVal:percentCompleted}) } }; //未封装 // axios.post("http://vueshop.glbuys.com/api/user/myinfo/formdatahead?token=1ec949a15fb709370f",data,config).then(res=>{ // console.log(res); // if (res.data.code===200){ // alert("上传成功") // this.setState({showHead:"http://vueshop.glbuys.com/userfiles/head/"+res.data.data.msbox}) // } // }); //封装ajax request("url","file", {headfile:headFile},config).then(res=>{ console.log(res); if (res.code===200){ alert("上传成功"); this.setState({showHead:"uri"+res.data.msbox}); } }) }
fetch请求
get方式
复制代码
1
2
3
4
5
6
7
8fetch("url").then(res=>res.json()).then(res=>{ console.log(res); if(res.code===200) { //navs是定义的一个数组接收 this.setState({navs: res.data}); } })
post方式
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18let data=new FormData(); data.append("headfile",headFile); fetch("url",{ method:"post", //若为RAW则不用写headers // headers:{ // 'Content-Type':"application/x-www-form-urlencoded" // }, body:data, }).then(res=>res.json()).then(res=>{ console.log(res); if (res.code===200){ alert("上传成功"); this.setState({showHead:"uri"+res.data.msbox}); } })
fetch无法写进度条,裂开。
最后
以上就是坦率水杯最近收集整理的关于React框架封装一个axios请求的方式和fetch请求方式的全部内容,更多相关React框架封装一个axios请求内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复