shr

Simple HTTP requests for browser. "Simple requests" don't trigger a CORS preflight.

Usage no npm install needed!

<script type="module">
  import shr from 'https://cdn.skypack.dev/shr';
</script>

README

shr

Simple HTTP requests for browser. "Simple requests" don't trigger a CORS preflight.

Build Status Coverage Status

Installation

npm install shr --save

Example

import client from 'shr'

client
  .get('https://api.example.com/users')
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

Documentation

To avoid preflight requests, data is serialized using qs library and sent with Content-Type header as application/x-www-form-urlencoded. PUT, PATCH and DELETE requests are made as POST requests with an additional field _method set to the method name which needs to be supported by the backend.

Available Methods

import { create } from 'shr'

const client = create(options)

client.request(url, options)
client.get(url, params, options)
client.post(url, data, options)
client.put(url, data, options)
client.patch(url, data, options)
client.delete(url, data, options)

Options

{
  baseURL: '',

  method: 'get',

  params: {},

  data: {},

  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  },

  transformRequest(data) {
    return data
  },

  transformResponse(data) {
    return data
  },

  isValid: ({ status }) => status >= 200 && status < 300,

  timeout: 0,

  withCredentials: false,

  responseType: 'json',

  onDownloadProgress: () => {},

  onUploadProgress: () => {},
}

Response

{
  data: {},
  status: 200,
  statusText: 'OK',
}

Error

{
  message: '',
  response: {},
}

License

MIT