Wrapper on m.request

by osban

Level: beginner • Mithril.js Version: latest

This is an example showing a wrapper for Mithril.js' m.request that allows an easier and snappier api handling. Especially the possibility of adding custom handlers to specific http status codes is a plus.

Live Example


Type Name URL


// m.request wrapper api.js
const handlers = {
  500: err => console.error(err.code, err.response)

const request = method => (url, options) =>
    url: 'https://example.com' + url,
    ...options // might need Object.assign for Edge
    .catch(err => {
      if (err.code in handlers) handlers[err.code](err)
      else throw err

export default {
  get   : request('GET'),
  put   : request('PUT'),
  post  : request('POST'),
  delete: request('DELETE')

// usage
import api from './api'


api.post('/bar', {
  headers: {'Header1': 'header'},
  body: {foo: 'foo'}

The snippet requires the latest version of Mithril.js framework. It is ideal for beginners showing some basic recipes.

In this example we can see an example of Mithril.js' m.request API method, besides it core m() hyperscript function.

The code sample was authored by osban. It was last modified on 24 September 2020. Want to see more examples written by osban? Then Click here.


Do you see some improvements, that could be addressed here? Then let me know by opening an issue. As an alternative, you can fork the repository on GitHub, push your commits and send a pull request. To start your work, click on the edit link below. Thank you for contributing to this repo.

See more code examples  •  Edit this example on GitHub