封装及调用fetch
一、封装fetch
创建fetch/index.js
import 'whatwg-fetch' import 'es6-promise' export function get(url) { let result = fetch(url, { credentials: 'include', headers: { 'Access-Control-Allow-Origin': '*', 'Accept': 'application/json, text/plain, */*' }, // 设置允许cors跨域 mode: 'cors' }); return result; } // 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式 function obj2params(obj) { let result = ''; let item; for (item in obj) { result += '&' + item + '=' + encodeURIComponent(obj[item]); } if (result) { result = result.slice(1); } return result; } // 发送 post 请求 export function post(url, paramsObj) { let result = fetch(url, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, body: obj2params(paramsObj) }); return result; }
二、调用fetch
1、使用then
import {get} from '../fetch/index'; get("./mock/list.json").then((res) => { return res.json(); }).then((json)=>{ this.setState({ dataList: json.data }) }).catch(function (err) { console.log(err); })
二、async、await
import {get} from '../fetch/index'; let login = async () => { try { let json = await post("#", { password: password, username: username }); let data = await json.json(); console.log(data); } catch (err) { console.log(err) } } login()