Skip to content
Advertisement

TypeError: axiosCookieJarSupport is not a function, works in Node.JS but not .vue pages?

I have a function to authenticate with a website, it works when I run it in a basic node.js script but it does not work when run from a .vue page (using NuxtJS framework).

When I run it in a .vue page it receives errors stating TypeError: axiosCookieJarSupport is not a function

Examples below.

Working code in basic .js file:

const axios = require("axios").default;
const axiosCookieJarSupport = require("axios-cookiejar-support").default;
const tough = require("tough-cookie");
const qs = require("qs");

async function main() {
  let session = axios.create({
    withCredentials: true,
    baseURL: "xxx",
  });

  axiosCookieJarSupport(session);
  session.defaults.jar = new tough.CookieJar();

  let res = await session.post("/api/auth/login", qs.stringify({username: '', password: ''}))
    .then((res) => {
      console.log(res);
    })
}

main();

Code in .vue page that is not working:

<script>
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const tough = require('tough-cookie')
const qs = require('qs')

export default {
  methods: {
    async login () {
      const session = this.$axios.create()

      axiosCookieJarSupport(session) // <-- error occurs here

      session.defaults.jar = new tough.CookieJar()

      const res = await session.$post('/api/auth/login', qs.stringify({ username: '', password: '' }))
        .then((res) => {
          console.log(res)
        })
    }
  }
}
</script>

I’ve tried moving the const axiosCookieJarSupport = require('axios-cookiejar-support').default into the function but it made no difference.

Any help would be much appreciated.

Advertisement

Answer

Fixed by updating my nuxt.config.js file with:

axios: {
    credentials: true,
    proxy: true,
    jar: true // <-- this was missing
  },

The code in the .vue page is now:

<script>
export default {
  methods: {
    async login () {
      const qs = require('qs')
      const session = this.$axios.create()
      await session.$post('/api/auth/login', qs.stringify({ username: '', password: '' })).then((res) => {
        console.log(res)
      })
  }
}
</script>

It appears to now be storing the session and I can use session on subsequent api calls.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement