React中的数据请求
- xhr
- jQuery中的$.ajax
- axios
- fetch
fetch是ES6提供的一个数据请求方法,是属于浏览器自带的方法,存在一定的兼容性问题。
一般情况下会引入第三方封装的fetch : whatwg-fetch
cnpm install whatwg-fetch
- 特点
- 返回promise
- 留给来开发者足够的操作空间
- fetch请求成功以后不会直接将数据返回给
.then()
,而是将一个未处理的结果集返回给用户。因此我们需要在第一个.then
中解析数据,在第二个.then
中获取数据- 默认是不会携带cookie的需要配置
credentials:"include"
- 语法:
import {fetch as fetchPro} from "whatwg-fetch"
get:
fetch(url,{
headers:{}
}).then(()=>{}).then(()=>{})
import qs from "qs"//安装qs:cnpm i qs
post:
fetch(url,{
methods:"post",
headers:{
"content-type":"application/x-www-form-urlencoded"
}
body:存放post提交的参数
}).then(()=>{}).then(()=>{})
- 二次封装
import { fetch as fetchPro } from "whatwg-fetch";
import qs from "qs";
const get = (options) => {
var str = "";
var path = "";
if (options.data) {
for (var key in options.data) {
str += `&${key}=${options.data[key]}`;
}
}
path = options.url + "?" + str.slice(1);
return fetchPro(path, {
headers: {
...options.headers,
"content-type": "application/json"
},
credentials: "include"
}).then(res => res.json())
}
const post = (options) => {
return fetchPro(options.url, {
method: "post",
headers: {
...options.headers,
"content-type": "application/x-www-form-urlencoded"
},
credentials: "include",
body: qs.stringify(options.data)
}).then(res => res.json())
}
export default {
get,
post
}
网友评论