fetch 简单封装,并使用

19 篇文章 0 订阅
4 篇文章 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('&')
    }
  }
  if (params?.method?.toLowerCase() == 'POST') {
    data = JSON.stringify(data)
  }
  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)
      })

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

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值