欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

对Fetch进行简单的二次封装

程序员文章站 2022-03-11 16:36:01
...

新建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
    })
  }
}
相关标签: fetch