Vue Login with Axios
May 15, 2020
In this tutorial, you'll learn how to build a Vue form that authenticates using HTTP basic auth and Axios.
Setup with Axios
HTTPBin offers a free sample endpoint to test basic auth. The endpoint URL includes the correct username and password for test purposes. For example, the URL https://httpbin.org/basic-auth/foo/bar
succeeds if you send it properly formatted basic auth for username 'foo' and password 'bar', and fails if you don't.
If you pass the auth
option to axios.get()
, Axios will automatically format basic auth.
const res = await axios.get('https://httpbin.org/basic-auth/foo/bar', {
// Axios looks for the `auth` option, and, if it is set, formats a
// basic auth header for you automatically.
auth: {
username: 'foo',
password: 'bar'
}
});
res.status; // 200
Vue Login Form
Building a form in Vue is easy: just use v-model
. When the user submits the login form, call the login()
method
that uses the above Axios logic.
const app = new Vue({
data: () => ({
username: '',
password: '',
error: null,
success: false
}),
methods: {
login: async function() {
const auth = { username: this.username, password: this.password };
// Correct username is 'foo' and password is 'bar'
const url = 'https://httpbin.org/basic-auth/foo/bar';
this.success = false;
this.error = null;
try {
const res = await axios.get(url, { auth }).then(res => res.data);
this.success = true;
} catch (err) {
this.error = err.message;
}
}
},
template: `
<form @submit="login()">
<h1>Login</h1>
<div>
<input type="string" placeholder="Username" v-model="username">
</div>
<div>
<input type="password" placeholder="Password" v-model="password">
</div>
<div v-if="error">
{{error}}
</div>
<div v-if="success" id="success">
Logged in Successfully
</div>
<button type="submit">Submit</button>
</div>
`
});
Vue School has some of our favorite Vue
video courses. Their Vue.js Master Class walks you through building a real
world application, and does a great job of teaching you how to integrate Vue
with Firebase.
Check it out!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!