fetch记录一下子

1.原生http请求

    var url = 'https://b2b.pre.choicesaas.cn/choice-b2b/purchase/querySaleOrderList';
      var __req = null;
    if (window.XMLHttpRequest){
      __req = new XMLHttpRequest();
    } else if (window.ActiveXObject){
      __req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(__req){
      __req.onreadystatechange = function(){
        if(4 == __req.readyState){
            if(200 == __req.status){
              if('function' == typeof cb){
                cb(__req.responseText);
              }
            }else{

            }  
        }
    };
    __req.open("GET", url, true); // 1 请求方式 2  请求地址 3 是否异步
    __req.send(null);
   }

2.fetch请求

    const fetch1 = function ({url, ...params}) {
        return new Promise((reslove, reject) => {
          fetch(url, {
            ...params,
            // credentials: 'include',
          }).then(res => {
            if (res.ok) { 
              reslove(res.json());
            } else {
              reject(res);
            }
          }).catch(err => {
            reject(err);
          })
        });
      }
      const obj = {
        fetchPost: async function() {
          const url = 'http://localhost:3003?callback=handleBack';
          const res = await fetch1({
            method: 'POST',
            url,
          });
          console.log('---res', res);
        }
      }

  obj.fetchPost();

3.上面是封装多得fetch,直接使用的fetch

    fetch('http://localhost:3003').then(res => {
    // console.log('---res', res.json()); 
    // 一个then里面不能同时操作两次和两次以上的res
    // 同时使用多次就会报错 ---> index.html:43 Uncaught (in promise) TypeError: body stream already read
    // throw new Error('test');
    return res.json(); // 是一个promise对象
  }).then(res => {
    console.log('----dddd', res);
  });
  
  // --------------下面是form上传时候------------------
  
 const formData = new FormData();
      formData.append('oper_id', '11');  
      formData.append('oper_name', 'kong');
      const obj = {a: '1', b: '2'};
      fetch('http://localhost:3003', {
        method: 'POST',
        body: formData,
      }).then(res => {
        // console.log('---res', res.json());
        // throw new Error('test');
        return res.json();
      }).then(res => {
        console.log('----dddd', res);
      })
    // -------请求头
    // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryTYuWBZ9zVtyRNm5q
    // -------

fetch请求对某些错误http状态不会reject封装一下

// 服务器返回 400,500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,fetch 才会被 reject
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}
function parseJSON(response) {
  return response.json();
}
export default function request(url, options) {
  let opt = options||{};
  return fetch(url, {credentials: 'include', ...opt})
    .then(checkStatus)
    .then(parseJSON)
    .then((data) => ( data ))
    .catch((err) => ( err ));

http请求头中的content-type

  1. application/json
    传递的是一个json对象,并不是直接丢一个对象过去,需要进行序列化,JSON.stringify(data)

  2. application/x-www-form-urlencoded
    例如我们发送一个登录请求,参数是{user:1234,pwd:1234},最终提交服务器的是user=1234&pwd=1234

  3. multipart/form-data
    ------WebKitFormBoundaryPQAsHbjoSqoJ1WXl
    Content-Disposition: form-data; name="oper_id"

    11
    ------WebKitFormBoundaryPQAsHbjoSqoJ1WXl
    Content-Disposition: form-data; name="oper_name"

    kong
    ------WebKitFormBoundaryPQAsHbjoSqoJ1WXl--

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,987评论 19 139
  • Address:https://www.zybuluo.com/XiangZhou/note/208532 Exp...
    天蠍蒗漫阅读 11,405评论 2 55
  • # 一度蜜v3.0协议 --- # 交互协议 [TOC] ## 协议说明 ### 请求参数 下表列出了v3.0版协...
    c5e350bc5b40阅读 672评论 0 0
  • 转发自:http://shanshanpt.github.io/2016/05/03/go-gin.html gi...
    dncmn阅读 6,086评论 0 1
  • 已经凌晨了,虽然很困但还是不想睡。如今的我,没什么追求,没什么爱好,什么都没有。浑浑噩噩的生活,忍受着一切该忍受的...
    槡魚⺄晚阅读 163评论 0 0