fetch简单封装request.js

const prefixUrl = 'http://test-api.xxx.com'//测试 // constprefixUrl='https://api.xxx.com'//生产 //get请求封装 const fetchGet = function ({url, params}) { let list = []; for (let key in params) { let str = `${key}=${params[key]}` list.push(str); } const data = https://www.it610.com/article/list.join('&'); let allUrl = `${prefixUrl + url}?${data}`; const options = { method: 'GET', headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=UTF-8', }, } return fetch(allUrl, options).then(res => { return res.json(); }).catch(err => { console.log(err); }); }; // post请求封装 const fetchPost = function ({url, params}) { const options = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=UTF-8', }, body: JSON.stringify(params), } return fetch(prefixUrl + url, options).then(res => { return res.json(); }).catch(err => { console.log(err); }) }; export { fetchGet, fetchPost, }

【fetch简单封装request.js】api.js使用
import {fetchGet} from './request'export function getXXX(params) { return fetchGet({ url:'/xxxxx', params:params }) }

    推荐阅读