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:
JavaScript
x
22
22
1
const axios = require("axios").default;
2
const axiosCookieJarSupport = require("axios-cookiejar-support").default;
3
const tough = require("tough-cookie");
4
const qs = require("qs");
5
6
async function main() {
7
let session = axios.create({
8
withCredentials: true,
9
baseURL: "xxx",
10
});
11
12
axiosCookieJarSupport(session);
13
session.defaults.jar = new tough.CookieJar();
14
15
let res = await session.post("/api/auth/login", qs.stringify({username: '', password: ''}))
16
.then((res) => {
17
console.log(res);
18
})
19
}
20
21
main();
22
Code in .vue page that is not working:
JavaScript
1
24
24
1
<script>
2
const axiosCookieJarSupport = require('axios-cookiejar-support').default
3
const tough = require('tough-cookie')
4
const qs = require('qs')
5
6
export default {
7
methods: {
8
async login () {
9
const session = this.$axios.create()
10
11
axiosCookieJarSupport(session) // <-- error occurs here
12
13
session.defaults.jar = new tough.CookieJar()
14
15
const res = await session.$post('/api/auth/login', qs.stringify({ username: '', password: '' }))
16
.then((res) => {
17
console.log(res)
18
})
19
}
20
}
21
}
22
</script>
23
24
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:
JavaScript
1
6
1
axios: {
2
credentials: true,
3
proxy: true,
4
jar: true // <-- this was missing
5
},
6
The code in the .vue page is now:
JavaScript
1
14
14
1
<script>
2
export default {
3
methods: {
4
async login () {
5
const qs = require('qs')
6
const session = this.$axios.create()
7
await session.$post('/api/auth/login', qs.stringify({ username: '', password: '' })).then((res) => {
8
console.log(res)
9
})
10
}
11
}
12
</script>
13
14
It appears to now be storing the session and I can use session on subsequent api calls.