axios equivalent of curl -u flag

Viewed 1225

I am trying to implement a frontend in axios for a backend that gives frontend example in curl. What would the axios equivalent of the following be? I am not sure how to represent the -u flag.

curl -X POST http://0.0.0.0:9000/auth -i -u test@example.com:123456
1 Answers

The -u or --user flag in curl is used to:

Specify the user name and password to use for server authentication.

Following that reasoning the property you're looking for is auth within axios, an example:

axios('https://example.com', {
  auth: {
   username: 'john.doe',
   password: 'penny_lane',
  }
})

Here's the reference to the axios documentation.

Note that axios only automatically creates the authorization headers from auth:{...} on GET requests. If you want to generate the same header on a POST you will have to make it directly.

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

const url = 'https://...'
const data = {
  ...
}

axios.post(url, data, {
  headers: {
    'Authorization': `Basic ${token}`
  },
})
Related