1. 程式人生 > >在現有專案中使用fetch

在現有專案中使用fetch

基於做前端現在不用fetch就out的心態,我決定再現有的AngularJS專案中使用fetch代替angularJs的$http()方法

使用fetch封裝成一個可以公用的js檔案

import 'whatwg-fetch';
import 'es6-promise';
import 'promise-polyfill';
import 'isomorphic-fetch';

const objToQueryString = obj => {
  let result = '';
  for (let key in obj) {
    result += '&' + key + '=' + encodeURIComponent(obj[key]);
  }
  if (result) {
    result = result.slice(1);
  }
  return result;
};

const checkStatus = response => {
  if ((response.status >= 200 && response.status < 300) || response.status === 304) {
    return response;
  }
  const url = response.url;
  const queryPos = url.indexOf('?');
  let urlDo;
  if (queryPos > 0) {
    urlDo = url.substring(url.lastIndexOf('/') + 1, queryPos);
  } else {
    urlDo = url.substring(url.lastIndexOf('/') + 1);
  }
  throw new Error(`呼叫介面${urlDo}出錯, 錯誤碼${response.status}`);
};

export const get = (url, paramsObj) => {
  if (paramsObj) {
    url = url + '?' + objToQueryString(paramsObj);
  }
  return fetch(url, {
    method: 'GET',
    credentials: 'include',
    headers: {
      'Accept': 'application/json, text/plain, */*'
    },
  })
    .then(checkStatus)
    .then(response => response.json());
};

export const post = (url, paramsObj, bodyObj) => {
  if (paramsObj) {
    url = url + '?' + objToQueryString(paramsObj);
  }
  return fetch(url, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: objToQueryString(bodyObj)
  })
    .then(checkStatus)
    .then(response => response.json());
};

封裝成一個可以公用的js檔案的好處就是,每次使用fetch,只需要呼叫 fetch.js檔案export出去的get方法或者post方法即可

具體使用

1,引入fetch.js檔案

import {get, post} from '../../../utils/fetch';

2,呼叫get方法

 getLeaderOpinion(params) {
        get(path.offical.getLeaderOpinion, params).then(data=>{
            
          });
      },