1.0.2 • Published 3 years ago

@juxi/app-network v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

App 网络通用配置

基于 App采用 React Native 和 小程序采用Taro技术栈进行开发。两者的技术栈都是基于React。 所以抽离部分网络api到公共组件中。实现两端业务同步。

项目文件介绍

  • http-config: 项目配置
  • http-encoding: 编码方式(URLEncoding, JSONEncoding)
  • http-method: 常用的方法,采用全大写
  • http-header: 常用的便捷header
  • request文件: 存放各个业务场景的请求参数,根据业务不断添加

设计思路

header、method、config 封装常用的方法、常量。

http-encoding

主要针对 params。

  • URLEncoding: 把 params 转成 xx=xx&xx=xx的形式拼接在url的query部分(方便的可以直接在url后面自己拼接,不通过params的方式)
  • JSONEncoding: 把 params 转成data 放在 body 部分

request文件

单个request文件存放某类业务相似的请求。最好和后端文档同步。用户类请求相关的api放到同个文件下, 命名为 http-request-xxx.js。 不同业务的api,单独新开一个文件。

举个🌰

export const HTTPRequestGoods = {
    // 对应单个api
    get: (keyword) => {
        return {
            url: HTTPBaseURL + '?seach=' + keyword,
            params: null,
            method: HTTPMethod.GET,
            encoding: HTTPEncoding.JSONEncoding,
            header: null
        }
    },
    add: (name) => {
        url: HTTPBaseURL + '/add'
    }
    .
    .
    .
    .

}

按照以下格式去实现

{
    url: 必要
    params: 可选
    method: 可选
    encoding: 可选
    header: 可选
}

命名关键字: get、update、delete、add

具体使用

App端 为例,首先需要对网络api进行进一步封装

RN 项目封装(仅供参考):

// HTTP.js 文件
export function request(config, success, failure, completion) {
    let url = config.url
    let encoding = config.encoding || HTTPEncoding.URLEncoding
    let method = config.HTTPMethod || HTTPMethod.GET
    let header = config.header || DefaultHeader
    return axios.request({
        url: config.url,
        method: method,
        params: props.params,
        header: header
    })
}

上传调用

// 使用的时候
let config = HTTPRequestUser.login(phone, password)
HTTP.request(config, (response) => {

},(error) => {

  })
1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago