npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

min-fetch

v3.0.0

Published

Promise Based request / fetch / http For Real Project, Support multiple platforms

Downloads

50

Readme

@chunpu/http

NPM version Downloads Dependency Status

Promise Based request / fetch / http For Real Project, Support multiple platforms

Installation

npm i @chunpu/http

CircleCI

Features

Inspired by axios

Send Http Request just like axios in 微信小程序, 快应用, jQuery, or XMLHttpRequest by default

Let's have the Same Experience with Request Data😜

Usage

import http from '@chunpu/http'

http.init({
  baseURL: 'https://my.domain'
})

http.get('/data').then(({data}) => {
  console.log(data)
})

Create Custom Http Instance

const anotherHttp = http.create({
  baseURL: 'https://my.domain'
})

Api

Simple Request

  • .get(url, config)
  • .delete(url, config)
  • .head(url, config)
  • .options(url, config)

Careful! There is no such api like .get(url, params)

Request with Data

  • .post(url, data, config)
  • .put(url, data, config)
  • .patch(url, data, config)

Basic Request

  • .request(config)
  • .request(url, config)

All config param is not required

Request Object

  • data data for request body
  • headers request headers
  • method request http method, default GET
  • params the url querystring object
  • timeout request timeout, 支持快应用和微信小程序
  • withCredentials whether use cors, default false

Automatic Transform Request Data

Respect the request headers['content-type'] setting, data will be transform by the content type, Plain Object data will be auto stringify

  • application/json will JSON.stringify the data object
  • application/x-www-form-urlencoded will qs.stringify the data object

data also support FormData, Blob, String

Response Object

  • data response data
  • headers name: value headers, all header names are lower cased
  • status status code, number
  • config the request object

Not Respect the response headers['content-type'] value, will always try to JSON.parse the data, because most server not respect the response mime

Platform Support

微信小程序

import http from '@chunpu/http'

http.init({
  baseURL: 'https://my.domain',
  wx: wx
})

http.get('/data').then(({data}) => {
  console.log(data)
})

支持单个请求超时设置

请通过 npm 安装, 参见 npm 支持

快应用

import http from '@chunpu/http'
import fetch from '@system.fetch'

http.init({
  baseURL: 'https://my.domain',
  quickapp: fetch
})

支持单个请求超时设置

记得在 manifest.json 文件中加入权限

"features": [
  { "name": "system.network" },
  { "name": "system.fetch" }
]

axios (node.js)

const axios = require('axios')
import http from '@chunpu/http'

http.init({
  baseURL: 'https://my.domain',
  axios: axios
})

Please use http with axios mode in Node.js platform

jQuery / Zepto

import http from '@chunpu/http'

http.init({
  baseURL: 'https://my.domain',
  jQuery: $
})

Config Defaults / Init

// support axios style
http.defaults.baseURL = 'https://my.domain'
http.defaults.timeout = 1000 * 20

// can also use http.init
http.init({
  baseURL: 'https://my.domain',
  timeout: 1000 * 20
})

Config default Post request Content-Type

default is JSON

Always stringify Data to JSON

http.defaults.headers.post['Content-Type'] = 'application/json'

Always stringify Data to querystring, which can really work not like axios...

http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

Interceptors

import http from '@chunpu/http'

http.init({
  baseURL: 'https://my.domain'
})

http.interceptors.request.use(config => {
  // Do something before request is sent
  return config
})

http.interceptors.response.use(response => {
  // Do something with response
  return response
})

Cancel Requests

compatible with axios Cancellation

For easy understanding, cancelToken equals deferred equals source.token

const source = http.CancelToken.source()

http.get('/very/slow/api/1', {
  cancelToken: source.token
}).catch(err => {
  console.error(err) // error: cancel request
})

http.get('/very/slow/api/2', {
  cancelToken: source.token
}).catch(err => {
  console.error(err) // error: cancel request
})

setTimeout(() => {
  source.cancel('cancel request') // will cancel all requests with this source
}, 1000)

Usage With Real Project

Assume the my.domain service always return data like this

{
  code: 0,
  message: 'ok',
  data: {
    key: 'value'
  }
}
import http from '@chunpu/http'

http.init({
  baseURL: 'https://my.domain'
})

http.interceptors.response.use(response => {
  if (typeof response.data === 'object') {
    // always spread the response data for directly usage
    Object.assign(response, response.data)
  }
  return response
})

http.post('/user/1024', {
  name: 'Tony'
}).then(({data, code, message}) => {
  if (code === 0) {
    return data
  } else {
    console.error('error', message)
  }
})

Usage with Vue.js

import http from '@chunpu/http'

Vue.prototype.$http = http

// in vue component file
submit () {
  this.$http.post('/user/1024', {name: 'Tony'}).then(({data}) => {
    this.user = data
  })
}

Handling Errors

All Platform support timeout error for one request

http.get('/very/slow/api').catch(err => {
  if (/timeout/i.test(err.message)) {
    // this is timeout error
  }
})

Other Api

You can stringify query string by

import http from '@chunpu/http'

http.qs.stringify({
  query: 'string'
})
// => 'query=string'

License

License