Reputation: 458
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.
Upvotes: 1
Views: 3227
Reputation: 458
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.
Upvotes: 1
Reputation: 29172
Because this library doesn't work in the browser:
Browser
Running on browser, this library becomes noop (config.jar might be ignored).
Upvotes: 2