牛骨文教育服务平台(让学习变的简单)
博文笔记

浏览器原生Fetch方法封装

创建时间:2018-01-11 投稿人: 浏览次数:221

浏览器原生的fetch方法是一种promise形式的异步交互方法
目前大部分浏览器都已支持(IE我没说你)
fetch.js文件

export function obj2params (obj) {
  let result = ""
  for (let item in obj) {
    result += `&${item}=${encodeURIComponent(obj[item])}`
  }
  return result ? result.slice(1) : result
}

export const post = (url, paramsObj) => {
  return _fetch(url, "POST", paramsObj)
}

export const get = (url, paramsObj) => {
  return _fetch(url, "GET", paramsObj)
}

export const _fetch = (url, method, paramsObj) => {
  return fetch(url, {
    method: method,
    /* 携带cookie */
    credentials: "include",
    headers: {
      "Accept": "appliaction/json,text/plain,*/*",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: obj2params(paramsObj)
  }).then(res => {
    if (res.status === 200) return res.json()
    res.text().then(text => {
      return Promise.reject(new Error(`${url}-->${text}-->${res.status}`))
    })
  })
}

调用部分

import { post } from "xxx/xxx/fetch"

post("url", {/* 这里是json数据 */}).then(res=>{
    //to do Sth
}).catch(err=>{
    console.error(err)
})

不要问我为什么没加分号
因为我的语法检查工具会——–>报错..

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。