Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active March 19, 2020 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/6c908b4413ce2f78aaabff19b7631b0c to your computer and use it in GitHub Desktop.
Save bradoyler/6c908b4413ce2f78aaabff19b7631b0c to your computer and use it in GitHub Desktop.
Simple Rest API client for node with support for JWT (bearer authentication) - requires Axios

REST-client.js

Usage

const RestClient = require('./rest-client')
const client = RestClient({ baseURL: 'https://mydomain.com' })
client.setAuthHeader('my-auth-token') // optional

const { data } = await client.get('/articles')

Request Debugging

Node:

export DEBUG=rest-client

Browser:

localStorage.debug = 'rest-client'
const debug = require('debug')('rest-client')
const axios = require('axios')
const https = require('https')
module.exports = ({ baseURL, timeout = 20000 } = {}) => {
if (!baseURL) {
baseURL = 'https://localhost:5001/api'
}
const instance = {}
let bearerToken = null
const config = {
baseURL,
timeout,
httpsAgent: new https.Agent({ rejectUnauthorized: false })
}
const $http = axios.create(config)
$http.interceptors.request.use((config) => {
if (bearerToken) {
config.headers.Authorization = `Bearer ${bearerToken}`
}
debug('request ->', config.headers.Authorization, config.method.toUpperCase(), config.baseURL + config.url)
return config
})
instance.get = (url) => $http.get(url)
instance.delete = (url) => $http.delete(url)
instance.post = (url, data) => $http.post(url, data)
instance.put = (url, data) => $http.put(url, data)
instance.setAuthHeader = (token) => { bearerToken = token }
// factory instance
return instance
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment