It's really messing me up... I'm feeling so frustrated. How can I utilize the 'validToken' variable in order to add it to the authorization line for headers? It seems to catch an error message in the fetchHeaders function...
I am baffled as to why the authentication with 'axios' isn't working for the authorized request (it keeps returning 'headers fetched with error!'), but it works fine if I hardcode the validToken value.. The validToken is returned correctly within the template though...
Please, I need some assistance! Thank you in advance!
#App.vue
<script>
import axios from 'axios';
const FormData = require('form-data');
const API_URL = "https://my_api_path.com/";
let data = new FormData();
data.append('username', 'my_username');
data.append('password', 'my_password');
let config = {
method: 'post',
url: `${API_URL}/login`,
data: data
}
let validToken = ""
export default {
data() {
return {
validToken: "",
headers: []
}
},
methods: {
async userLogin() {
try {
await axios(config)
.then((resp) => {
this.validToken = resp.data.access_token;
});
Token = this.validToken;
} catch(err) {
console.log(err)
}
},
async fetchHeaders() {
try {
let config = {
headers: {
Authorization: `Bearer ${validToken}`
}
}
const resp = await axios.get(`${API_URL}/headers/`,
config
)
this.headers = resp.data;
} catch (err) {
console.error("headers fetched with error!");
}
}
},
mounted() {
this.userLogin(),
this.fetchHeaders()
}
}
</script>