Search code examples
javascripttypescriptauthenticationaxiosbasic-authentication

How to call remote server with basic auth via axios?


I call a remote server with basic auth protected.

axios
  .get('http://localhost:9000/posts', {
    auth: {
      username: 'username'
      password: 'password'
    }}
  )
  .then(response => {
    console.log(response.data)
  })

This doesn't work. If set auth with default headers:

axios.defaults.auth = {username: 'username', password, 'password'}

Or post

axios.post('http://localhost:9000/posts', {}, {
  headers: { 'Authorization': + 'Basic ' + btoa('username' + ':' + 'password') }
}).then(function(response) {
  console.log('Authenticated')
}).catch(function(error) {
  console.log('Error on Authentication')
})

Neither of them can work.

From its Request Config, the set way is

auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

Where to put it?


Tried

axios({
  method: 'get',
  url: 'http://localhost:9000/posts',
  auth: {
     username: 'username',
     password: 'password'
  }
})
  .then(response => {
    console.log(response.data)
  })

Also got error No 'Access-Control-Allow-Origin' header is present on the requested resource.


Solution

  • axios({
     method: 'post',
     url: 'http://localhost:9000/posts', 
     auth: {
        username: 'username',
        password: 'password'
     }
    })
    

    should work! Check out this for more info.