在现有项目中使用fetch

本文介绍了如何在AngularJS项目中使用fetch替代$http服务,通过封装fetch为公共JS文件,简化调用过程。主要步骤包括创建fetch.js并导出get、post方法,然后在项目中引入并调用这些方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于做前端现在不用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=>{
            
          });
      },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值