0
点赞
收藏
分享

微信扫一扫

【前端】input表单 type属性详解

开源GIS定制化开发方案 03-20 14:00 阅读 1

前言

HarmonyOS 原生网络请求的用法比较麻烦,还是有必要封装下,先看它的原生写法:

// 引入包名
import http from '@ohos.net.http';

// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    "EXAMPLE_URL",
    {
        method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
        // 开发者根据自身业务需要添加header字段
        header: {
            'Content-Type': 'application/json'
        },
        // 当使用POST请求时此字段用于传递内容
        extraData: {
            "data": "data to send",
        },
        expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
        usingCache: true, // 可选,默认为true
        priority: 1, // 可选,默认为1
        connectTimeout: 60000, // 可选,默认为60000ms
        readTimeout: 60000, // 可选,默认为60000ms
        usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
    }, (err, data) => {
        if (!err) {
            // data.result为HTTP响应内容,可根据业务需要进行解析
            console.info('Result:' + JSON.stringify(data.result));
            console.info('code:' + JSON.stringify(data.responseCode));
            // data.header为HTTP响应头,可根据业务需要进行解析
            console.info('header:' + JSON.stringify(data.header));
            console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
            // 取消订阅HTTP响应头事件
            httpRequest.off('headersReceive');
            // 当该请求使用完毕时,调用destroy方法主动销毁
            httpRequest.destroy();
        } else {
            console.info('error:' + JSON.stringify(err));
            // 取消订阅HTTP响应头事件
            httpRequest.off('headersReceive');
            // 当该请求使用完毕时,调用destroy方法主动销毁。
            httpRequest.destroy();
        }
    }
);

这么一大挂,怎么看也不像 axios 那样 axios.get(url) 一行代码就能够请求了。原生的HarmonyOS 网络请求可能更偏向于提供底层功能,类似于 WEB 中的 XMLHttpRequest,对于前端比较习惯的可能是下面的方式:

import http from '../utils/http'

export const login = (params: any) => http.postForm('/api/example/login', params)

export const login2 = (params: any) => http.postJson('/api/example/login', params)

export const login3 = (params: any) => http.get('/api/example/login', params)

login({}).then(res => {
	// ...
})

简洁,非常简洁~ 下面我们来看看是怎么封装的。

封装

interface EasyHttpOptions {
  baseUrl?: string
  connectTimeout?: number
  readTimeout?: number
}

class EasyHttp {
  protected options: EasyHttpOptions = {
    baseUrl: '',
    connectTimeout: 6 * 1000,
    readTimeout: 6 * 1000
  }

  constructor(options: EasyHttpOptions = {}) {
    Object.assign(this.options, options)
  }

  request(url: string, options: http.HttpRequestOptions = {}) {
    const {baseUrl, connectTimeout, readTimeout} = this.options
    const httpRequest = http.createHttp()

    return new Promise<http.HttpResponse>((resolve, reject) => {
      httpRequest.request(
        baseUrl + url,
        {
          expectDataType: http.HttpDataType.OBJECT, // 可选,指定返回数据的类型
          connectTimeout, // 可选,默认为60000ms
          readTimeout, // 可选,默认为60000ms
          ...options
        }
      ).then(res => {
        if (res.code === 200) {
          const { code } = (res.result || {}) as any
          if (code === 0) {
            resolve(res)
          } else {
            reject(res)
          }
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  get(url: string, params: Record<string, any> = {}, options: http.HttpRequestOptions = {}) {
    return this.request(`${url}?${stringify(params)}`, {
      method: http.RequestMethod.GET,
      ...options
    })
  }

  postForm(url: string, data: Record<string, any>, options: http.HttpRequestOptions = {}) {
    return this.request(url, {
      method: http.RequestMethod.POST,
      extraData: stringify(data),
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      ...options
    })
  }

  postJson(url: string, data: Record<string, any>, options: http.HttpRequestOptions = {}) {
    return this.request(url, {
      extraData: data,
      method: http.RequestMethod.POST,
      header: {
        'Content-Type': 'application/json'
      },
      ...options
    })
  }
}

export default new EasyHttp({
  baseUrl: 'https://demo.example.com'
})

上面有个序列化方法 stringify 如下:

function stringify(obj: Record<string, any>) {
  return Object.keys(obj)
    .map((key) => `${key}=${encodeURIComponent(obj[key])}`)
    .join('&')
}

以上封装属于业务层的常规封装,值得注意的是:

正因如此,它才更有封装的必要性。

用法

const http = new EasyHttp({
  baseUrl: 'https://demo.example.com'
})

export const login = (params: any) => http.postForm('/api/example/login', params)

总结

尽管 HarmonyOS 开发生态(例:ohpm)目前尚显薄弱,但这正是我们展现创造力的绝佳时机。每个成熟的生态系统都需经历从无到有的过程,HarmonyOS 也不例外。希望 HarmonyOS 开发生态未来会更好,也希望会有更多的开发者能参与生态建设!

举报

相关推荐

0 条评论