admin管理员组

文章数量:1330395

I'm trying to use an API of which I have both username and password, through this code I can get the authentication token:

  axios.post(this.apiUrl,
            {
                username : 'xxx',
                password : 'yyy'
            },
  
  )
  .then((respond)=>{
    this.token = respond.data.token
    console.log(this.token)
  })
  .catch((error)=>{
    console.log('errore',error)
  })

since I need that token to access other routes in the same API, I should reuse it in other requests, as in this case:

  axios.post(this.apiUrl+(otherEndPoint),{body},
            {
              headers:{
                  "authorization":this.token
              }
            },
  
  )
  .then((respond)=>{
    r = respond.data.token
    console.log(r)
  })
  .catch((error)=>{
    console.log('errore',error)
  })

but it doesn't work; can someone help me?

I'm trying to use an API of which I have both username and password, through this code I can get the authentication token:

  axios.post(this.apiUrl,
            {
                username : 'xxx',
                password : 'yyy'
            },
  
  )
  .then((respond)=>{
    this.token = respond.data.token
    console.log(this.token)
  })
  .catch((error)=>{
    console.log('errore',error)
  })

since I need that token to access other routes in the same API, I should reuse it in other requests, as in this case:

  axios.post(this.apiUrl+(otherEndPoint),{body},
            {
              headers:{
                  "authorization":this.token
              }
            },
  
  )
  .then((respond)=>{
    r = respond.data.token
    console.log(r)
  })
  .catch((error)=>{
    console.log('errore',error)
  })

but it doesn't work; can someone help me?

Share Improve this question edited May 29, 2024 at 20:14 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 29, 2022 at 15:11 daxdax 311 gold badge1 silver badge2 bronze badges 3
  • i think you need to add Bearer before the token like so : Authorization: Bearer MyToken – Lk77 Commented Apr 29, 2022 at 15:24
  • 1 What doesn't work? Please describe the errors and format your question properly. – code Commented Apr 29, 2022 at 15:25
  • with postman if I use the token ,obtained from the first request ,inserting it in the value present in authorizations, I can get the data provided by the API...I have to be able to do the same thing with axios...provide the route of the second request with the token obtained from the first request to get the data – dax Commented Apr 29, 2022 at 15:46
Add a ment  | 

2 Answers 2

Reset to default 3

Not sure if you are looking for Bearer Token or x-api-key. Anyway, it should work like:

const token = "your token";
const res = await axios.post(URL, {data:"your_data"}, {
        headers: {
          // 'Authorization': `Bearer ${token}` 
          'x-api-key':`${token}`
        }
    })

In the code upper here, you have the 2 different auth methods, Bearer is mented.

with no background on how your project is setup, the gist on how to do it is the following steps:

  1. Create an axios instance (whether it be by using a CDN or importing axios from your project's installed packages)
  2. Set the axios default headers.
  3. Use the axios methods get, post, etc.

In code:

// Import axios module
import axios from 'axios';

// Set default header. e.g, X-API-KEY
axios.defaults.headers['X-API-KEY'] = 'some-api-key';

// Use axios as you would normally
axios.get('http://example./secure-endpoint')
    .then(res => console.log(res.data))
    .catch(err => console.log(err));

For your context:

import axios from 'axios';

// ... somewhere in code
// Get api-key from server
const username = 'someUsername';
const password = 'somePassword';
axios.post('http://example./api/getKey', {
    username,
    password
}).then(res => {
    axios.defaults.headers['x-api-key'] = res.data.apiKey;
})
.catch(err => console.log(err));
// ...

// ... somewhere else in code
axios.get('http://example./secure-endpoint')
    .then(res => console.log(res.data))
    .catch(err => console.log(err));
// ...

These are just examples. Change according to your project's structure and needs.

本文标签: javascriptapiKey and axiosStack Overflow