Git Product home page Git Product logo

taro-axios's Introduction

taro-axios NPM Version Build Status Coverage Status License

Taro 中使用 axios

源起

因为 Taro 不支持解析 package.json 里的 browser 属性,导致所有使用了该特性的包都可能无法在 Taro 里正常运行。不幸的是,axios 就是其中之一。

于是,taro-axios 预先解析了 axios 包中的 browser 属性并提供了 Taro 版的请求适配器后,将之打包出了一个 Taro 可用的版本。

也就是说,taro-axios 只是 axiosTaro 重制版,并非是为 Taro 仿写了一个 axiosaxios 提供什么,taro-axios 也就提供什么。

特性

  • 使用 TypeScript 编写,类型友好
  • 基于 Taro 适配器,天然支持多端
  • 支持 API 一致的多端上传文件

安装

# yarn
yarn add taro-axios

# 或, npm
npm i taro-axios --save

使用

使用方法同 axios

只不过你得这样引入 axios

import { axios } from 'taro-axios'
// 自版本 0.7.0 起你也可以这样引入:
// import axios from 'taro-axios'

axios
  .get('https://jsonplaceholder.typicode.com/todos/1')
  .then(res => {
    console.log(res.data)
  })

上传文件

为了支持多端上传文件,我们得引入 PostDataFileData 两个类,示例:

import { axios, PostData, FileData } from 'taro-axios'

async function uploadImage() {
  const { tempFilePaths } = await Taro.chooseImage({ count: 1 })
  Taro.showLoading({ title: '图片上传中...' })
  const res = await axios.post(
    'https://sm.ms/api/upload',
    new PostData({
      smfile: new FileData(tempFilePaths[0]),
      ssl: true,
      format: 'json',
    }),
  )
  Taro.hideLoading()
  Taro.showModal({
    title: '返回结果',
    content: JSON.stringify(res.data),
  })
}

许可

MIT © Jay Fong

taro-axios's People

Contributors

fjc0k avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.