首页 > 其他 > 详细

fetch 简单封装,并使用

时间:2021-08-06 17:48:47      阅读:27      评论:0      收藏:0      [点我收藏+]

几天才想起来前一段时间fetch的简单封装,今天简单记一下,话不多说直接上代码(结合了typescript不过不需要直接去除类型就行)

const url_base: string = "http://127.0.0.1:9097"

export async function request(params: API.RequestAPI) {

  let url: string = url_base + params?.url
  const method: string = params?.method
  const header: any = params?.header
  const data: any = params?.data
  const get_params: any = params?.params
  const get_params_list: Array<any> = []
  if (get_params) {
    for (const item in get_params) {
      get_params_list.push(item + "=" + get_params[item])
    }
    if (url.search(/\?/) === -1) {
      url += ‘?‘ + get_params_list.join(‘&‘)
    } else {
      url += ‘&‘ + get_params_list.join(‘&‘)
    }
  }
  const headers = {
    ‘Content-Type‘: ‘application/json‘,
    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    ...header
  }
  return await fetch(url, {
    method: method,
    // body: JSON.stringify(data),
    headers: new Headers(headers),
    mode: ‘cors‘,
    credentials: ‘omit‘,
    ...data
  })
    .then(res => { return res.json() })
    // .then(res => res.status)
    // .then(response => response.json())
    .catch(error => { return error })
}

使用,

// api
import { request } from "@/utils/request"

export async function getArticleList(params: any) {
  return request({
    url: ‘/getArticle/list‘,
    method: ‘GET‘,
    params
  })
}

//tsx -->vue
await getArticleList(params).then(res => {
      this.article_list = res?.data
      console.log(res?.data)
    })
      .catch(err => {
        this.$message({
          type: ‘success‘,
          message: "请求失败"
        })
        console.log(err)
      })

直接也会第一次封装,可能好多自己也都没考虑到,简单记录一下

本文连接:点击
博主个人小博客:嘿嘿

fetch 简单封装,并使用

原文:https://www.cnblogs.com/wwj0418/p/15107990.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!