'apiKey and axios
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, someone can help me
Solution 1:[1]
with no background on how your project is setup, the gist on how to do it is the following steps:
- Create an axios instance (whether it be by using a CDN or importing axios from your project's installed packages)
- Set the axios default headers.
- 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.com/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.com/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.com/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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Killerbee89 |
