javascriptaxios

How to use a token through out an API


I am having trouble with what I believe is asynchronous functions. I have some end points pointing towards a host with some requests to get a token from my login data, and another get request that uses that token to retrieve information about my profile.

The issue I believe I am having is that the login get request runs before my token is actually saved to my header variable. Is someone able to explain a way that I can wait for the token to be received before my API sends any other requests out?

const fastify = require('fastify')({ logger: true });
const axios = require('axios');
const fs = require('fs');
require('dotenv').config();

const username = process.env.USERNAME
const password = process.env.PASSWORD
let token
const instance = axios.create({
    baseURL: process.env.URL,
    headers : {
        'Authorization': `Bearer ${token}`
    }
})


async function login() {
    const response = await instance.post('/login', {username, password})
    token = response.data['token'];
    console.log(token);
}

async function me() {
    const response = await instance.get('/me')
    console.log(response.data);
}

login().then(me())

Solution

  • @noassl was correct with their comment. The real issue I was running into was with my incorrect assignment of the token. I changed the code to modify the instance properly.

    const fastify = require('fastify')({ logger: true });
    const axios = require('axios');
    const fs = require('fs');
    require('dotenv').config();
    
    const username = process.env.USERNAME
    const password = process.env.PASSWORD
    let token: string
    let instance: AxiosInstance = axios.create({
        baseURL: process.env.URL
    })
    
    async function login() {
        const response = await axios.post(`${process.env.URL}/login`, {username, password})
        token = response.data['token'];
        instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        console.log(token);
    }
    
    async function me() {
        const response = await instance.get('/me')
        console.log(response.data);
    }
    
    login().then(me())