Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active August 31, 2023 01:44
Show Gist options
  • Save ariesmcrae/e1fb751c9b78ed9649e64277dcce3ecd to your computer and use it in GitHub Desktop.
Save ariesmcrae/e1fb751c9b78ed9649e64277dcce3ecd to your computer and use it in GitHub Desktop.
Typescript: Basic auth (username/password) with Axios

Typescript: Basic auth (username/password) with Axios

// npm install axios

import axios, { AxiosInstance } from 'axios'

const axiosInstance: AxiosInstance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 3000,
  headers: {
    'Content-Type': 'application/json'
  }
})

const getData = async () => {
  const response = await axiosInstance.get('/posts/1', {
    auth: {
      username: 'ABC',
      password: 'DEF'
    }  
  })

  return response.data
}

void (async () => {
  const data = await getData()
  console.log(`data:${JSON.stringify(data, null, 2)}`)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment