Skip to content

Instantly share code, notes, and snippets.

@bradoyler bradoyler/rest-client.js
Last active Jan 7, 2019

Embed
What would you like to do?
Simple Rest API client for node with support for JWT (bearer authentication) - requires Axios
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
You can’t perform that action at this time.