对Fetch进行简单的二次封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35844177/article/details/78944692

新建request.js

import 'whatwg-fetch'
import 'es6-promise'

//let qs = require('qs');

const BASE_URL = '/api';

export function request(url, options) {
  options.credentials = 'include';
  options.headers = {
    'Accept': 'application/json, text/plain, */*',
  };

  if (options.method === 'POST' || options.method === 'PUT') {
   //根据后端接受什么形式的数据选择对应的body与headers
    options.body = JSON.stringify(options.body)
    options.headers = {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/json; charset=utf-8',
    }
    /* options.body = qs.stringify(options.body);
       options.headers={
       'Accept': 'application/json, text/plain, *!/!*',
       'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
       }
     */
  }

  url = `${BASE_URL}${url}`;

  return new Promise((resolve, reject) => {
    fetch(url, options).then(res => {
      return res.json();
    }).then(data => {
      resolve(data)
    }).catch(err => {
      //捕获异常
      console.log(err.msg);
      reject(err);
    })
  })
}

api.js

import {request} from "./request";

export default class Server{
  static getOrderListData(username) {
    let url = `/orderList/${username}`;
    return request(url,{method:'GET'})
  }

  static sendComment(id, comment) {
    let url = `/submitComment`;
    let data = {
      id: id,
      comment: comment
    };
    return request(url, {
      method: 'POST',
      body: data
    })
  }
}
阅读更多

扫码向博主提问

小小令

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • vue
  • 微信小程序
  • react
去开通我的Chat快问
换一批

没有更多推荐了,返回首页