首页 > 其他分享 >JS — fetch封装

JS — fetch封装

时间:2024-05-14 09:19:25浏览次数:21  
标签:const 请求 GET console fetch error 封装 JS response

function request(url, options = {}) {
  const defaultOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
    body: null,
  };

  const requestOptions = { ...defaultOptions, ...options };

  return fetch(url, requestOptions)
    .then(response => {
      const contentType = response.headers.get('content-type');
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      } else if (contentType && contentType.includes('application/json')) {
        return response.json();
      } else {
        return response.text();
      }
    })
    .catch(error => {
      console.error('请求失败:', error);
      throw error;
    });
}

// 使用示例
const apiUrl = 'https://jsonplaceholder.typicode.com/posts';

// 发起GET请求
request(apiUrl)
  .then(data => {
    console.log('GET请求成功:', data);
  })
  .catch(error => {
    console.error('GET请求失败:', error);
  });

// 发起POST请求
const postData = {
  title: 'foo',
  body: 'bar',
  userId: 1,
};
const postOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(postData),
};
request(apiUrl, postOptions)
  .then(data => {
    console.log('POST请求成功:', data);
  })
  .catch(error => {
    console.error('POST请求失败:', error);
  });

//将默认的请求选项定义为一个对象,并且在用户提供的选项和默认选项之间进行合并。
//根据响应的内容类型来决定是解析为JSON格式还是纯文本格式。

 

标签:const,请求,GET,console,fetch,error,封装,JS,response
From: https://www.cnblogs.com/qinlinkun/p/18190544

相关文章

  • 使用joinjs绘制流程图(八)-实战-绘制流程图+节点路径自定义
    效果图代码<template><divclass="app"><divref="myholder"id="paper"></div></div></template><script>import*asjointfrom'@joint/core'import$from'jque......
  • js播放背景音乐失败处理
    <script>constmusic=newAudio('med/CanonInD.mp3');music.loop=true;document.addEventListener("DOMContentLoaded",function(event){console.log("页面加载完毕"); if(music.paused){//console.log('音频......
  • SpringMVC中JSP页面不显示EL表达式的原因
    感谢 https://developer.aliyun.com/article/444366 在SpringMVC的入门项目中,这是最常见的问题。实际上这是因为使用了JSP1.2规范引起的。1.使用JSP1.2定义格式如果您使用了 老旧的JSP1.2描述方式,即使用了DTD定义:web.xml<!DOCTYPEweb-appPUBLIC"-......
  • Go:json-patch库讲解与应用
    Go:json-patch库讲解与应用原创 王义杰 运维开发王义杰 2024-05-1321:36 广东 听全文1.简介json-patch 是一个Go语言的库,用于处理JSON文档的修改。它实现了JSONPatch标准(RFC6902),允许对JSON文档进行部分更新,而无需重写整个文档。2.功能与特性操......
  • three.weapp.js提示applyMatrix4 is not a function
    最近做项目使用three.weapp,因为是微信版的three,所以删减了好多方法。在使用applyMatrix4时报了 applyMatrix4isnotfunction的错误。解决方法简单,找thee里面有的方法代替。先console.log查看下three.weapp里面的Group prototype有什么可以看到有一个applyMatrix方法。......
  • go封装zap日志
    log.gopackagexlogimport( "context" "fmt" "os" "runtime/debug" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore"rotatelogs"github.com/lestrrat-go/file-rotatelogs&qu......
  • autox.js脚本,采集抖音直播间评论信息
    autox.js脚本,采集抖音直播间评论信息auto();history={};console.show(true);while(true){listBox=className("androidx.recyclerview.widget.RecyclerView").findOne(2000);if(!listBox){continue;}allList=listBox.children();for(v......
  • autox.js脚本采集抓取抖音直播间弹幕评论
    利用autox.js识别抓取抖音直播间评论弹幕信息auto();history={};console.show(true);while(true){listBox=className("androidx.recyclerview.widget.RecyclerView").findOne(2000);if(!listBox){continue;}allList=listBox.children();f......
  • js 判断包含 对象属性
    在JavaScript中,判断一个对象是否包含某个属性可以使用in关键字,或者使用对象自身的hasOwnProperty方法。使用in关键字:letobj={name:'Alice',age:25};letpropertyName='name';if(propertyNameinobj){console.log(`对象包含属性:${propertyName}`);}else{......
  • vue 简易导出数据 vue-json-excel
    1、安装插件npminstall-Svue-json-excel2、注册importVuefrom"vue";importJsonExcelfrom"vue-json-excel";Vue.component("downloadExcel",JsonExcel);3、使用<a-buttonv-if="isExport"type="primary&quo......