网络请求

172 阅读1分钟

XMLHtttpRequest

axios

基于xmlhttprequest的一种封装

简单使用

```
```

最佳实践

封装基类

源码解析

Fetch

取消请求

useRequest Hooks

官网地址 useRequest hooks.umijs.org/zh-CN/hooks…

最佳实践:

封装请求基类

export function post(url: string, data = {}, options?: { [key: string]: any }) {
  return fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json, text/plain, */*;charset=UTF-8',
    },
    data: { ...data },
    urlPrefix: 'xxx',
    ...(options || {}),
  });
}

export function get(url: string, data = {}, options?: { [key: string]: any }) {
  return fetch(url, {
    method: 'GET',
    headers: {
      Accept: 'application/json, text/plain, */*;charset=UTF-8',
    },
    params: { ...data },
    ...(options || {}),
  });
}

发送请求接口

import { get, post } from './baseFetch'

export async function queryTableList(params: {name: string, id: string}) {
    return get('/xxx/xxx', params)
}

利用 useRequest Hooks 管理异步数据请求

    // 具体参考文档 https://hooks.umijs.org/zh-CN/hooks/async#%E9%A2%84%E5%8A%A0%E8%BD%BD
    
    1. 页面初始化的时候发送请求
    const { data, loading } = useRequest(() => {
        return queryTableList({
            name: 'daniel',
            id: '1'
        })
    })
    
    // data 为接口获取的数据
    
    2. 点击按钮的时候发送请求 (推荐)
    const getTableListRequest = useRequest(queryTableList,{
        manual: true,
    })
    
    const getData = () => {
        getTableListRequest.run({
         name: 'daniel',
         id: '1'
        }).then((res) => {console.log(res)})
    }
    
    useEffect(()=>{
        getData();
    },[])
    

JSONP

如何实现一个jsonp请求,创建一个script标签,利用src的跨域属性,利用回调函数获取数据仅支持get请求

实现代码

  const jsonp = (url, data = {}, callBack = 'callback') => {
      let paramsData = url.indexOf('?') === -1 ? '?' : '&';
      for (let key in data) {
          paramsData += `${key}=${data[key]}&`;
      }
      paramsData += 'callback=' + callBack;
      
      // 创建script标签挂载到window上去
      const newScript = document.createElement('script')
      newScript.src = url + paramsData;
      document.body.appendChild(newScript)
      
      return new Promise((reslove, reject) => {
          window[callback] = (data) => {
              try {
                  reslove(data)
              } catch (e) {
                  reject(e)
              } finally {
                  newScript.parentNode.removeChild(newScript)
              }
          }
      })
  }
  
  // 使用
  jsonp('https://photo.sina.cn/aj/index?a=1&page=1', {
      page: 1,
      cate: recommend
  }).then( res => console.log(res, '数据响应') )

postMessage

webscoket