fetch的请求封装

1,371 阅读1分钟

封装fetch请求

目录的划分(utils,api)

  • 将网络请求分成两个部分

    • 对于fetch的封装(utils/http.js)

      const qs = require('querystring')
      
      export function get(url) {
        return fetch(url).then(res => res.json())
      }
      
      export function post(url, prams) {
        prams = {
          method: 'post',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'content-type': 'application/x-www-form-urlencoded'
          },
          //将参数转化为由&连接的字符串
          body: qs.stringify(prams)
        }
        return fetch(url, prams).then(res => res.json())
      }
      
    • 对于请求函数的封装,让其引入到组件中就能通过.then或async await就能调用,不用传递任何参数

      • 对于路径的处理,放在api/base.js文件中

        export default base = {
          // 这里是公共路径http://iwenwiki.com/api/blueberrypai/getChengpinInfo.php
          baseUrl: 'http://127.0.0.1',
          // 下面是该项目的子路径
          // 例如商品路径
          category: '/category'
        }
        
      • 对于请求函数的封装放在api/index.js文件中

        import base from './base'
        import {get, post} from '../utils/http'
        
        /**
         * get方法只有一个url作为参数
         * 
         * post方法参数一是url, 参数二是传递的数据(对象)
         */
        
        // 这里是一些最终可用的网路请求函数
        
        export function getCategory() {
          let url = base.baseUrl + base.category
          return get(url)
        }
        
        
        export function postCategory() {
          let url = base.baseUrl + base.category
          return get(url, {
            username: 'zh',
            age: '20'
          })
        }