How can I get axios to maintain cookies/session between API calls?

12,600

Looks like the solution was right in front of my face:

https://github.com/3846masa/axios-cookiejar-support

Share:
12,600

Related videos on Youtube

D'Arcy Rail-Ip
Author by

D'Arcy Rail-Ip

VP of Technology @ CineSend. Message me if you're looking for a job!

Updated on June 04, 2022

Comments

  • D'Arcy Rail-Ip
    D'Arcy Rail-Ip almost 2 years

    I'm having trouble maintaining session state between axios calls in my NodeJS app. Here is the relevant code:

    const express = require("express")
    const cors = require("cors")
    const app = express()
    const initialize = require("@helpers/initialize")
    const { PORT } = require("@config")
    
    app.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', 'http://localhost:3001');
      res.header('Access-Control-Allow-Credentials', true);
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      next();
    })
    
    app.use(cors({
        origin: ['http://localhost:3001'],
        methods: ['GET', 'POST'],
        credentials: true
    }))
    
    app.listen(PORT, () => console.log(`> App listening on port ${PORT}!`))
    
    initialize()
    

    My helpers/initialize.js function, essentially stripped bare to troubleshoot:

    const axios = require("axios")
    const {
        CS_API,
        CS_COMMANDS: { LOGIN }
    } = require("@config")
    
    module.exports = () => {
        const loginURL = 'https://api.myhost.com/api/login'
        const getURL = 'https://api.myhost.com/api/active-jobs'
        const username = 'testusername'
        const password = 'testpassword'
        axios.defaults.withCredentials = true
        axios
            .post(loginURL, { username, password }, { withCredentials: true })
            .then(res => {
                if (res.status === 200) {
                    console.log('Successfully logged in.')
                    axios
                        .get(getURL, { withCredentials: true })
                        .then(res => {
                            console.log('Successfully maintained session state!')
                            console.log(res)
                        })
                        .catch(error => {
                            console.log('Failed to maintain session state!')
                            console.log(error.response.data)
                        })
                }
            })
            .catch(error => console.log(error))
    }
    

    Output received is:

    > App listening on port 3001!
    Successfully logged in.
    Failed to maintain session state!
    Device not logged in.
    

    The last output is from the API directly.

    What am I missing?