I am attempting to set up user login and role authentication with Vue, without using Vuex, as it's a bit much for the scope of our application. After a failed initial attempt to use jQuery AJAX outside of Vue, I resigned myself to making it work with Vue's data-oriented model, which I've been struggling with (I'm a designer by trade, not really a developer). My backend developer is writing in plain PHP and using mySQL, for reference.
Taking inspiration from this tutorial, I am trying to use v-model to send the form data to the server via axios.
Template:
<form class="login-form" id="loginform" @submit.prevent="login">
<div class="form-group space">
<label class="float-label" for="username">Username</label>
<input v-model="username" type="username" id="username" class="form-control" placeholder="username">
</div>
<div class="form-group">
<label class="float-label" for="username">Password</label>
<input v-model="password" type="password" id="password" class="form-control" placeholder="password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary float-right" id="login">Log in</button>
</div>
</form>
Script:
export default {
name: 'Login',
data () {
return {
username: '',
password: ''
}
},
methods: {
login: function () {
const loginInfo = { username, password }
console.log(loginInfo)
new Promise ((resolve, reject) => {
axios({url: 'api.com/index.php', data: loginInfo, method: 'POST' })
.then(resp => {
const token = resp.data.token
localStorage.setItem('user_token', token) // store the token in localstorage
const employeeId = resp.data.employee_id
localStorage.setItem('employee_id', employeeId) // store the id in localstorage
resolve(resp)
console.log(resp);
})
.catch(err => {
localStorage.removeItem('user_token') // if the request fails, remove any possible user token if possible
reject(err)
})
})
// myLoginRoutine(loginInfo).then(() => {
// this.$router.push('/')
// })
}
}
}
The request was going through no problem, but wasn't returning anything! I decided to check and see what I was sending him... and lo and behold, const loginInfo was not the input value, as expected, but {username: input#username.form-control, password: input#password.form-control}
I am, quite frankly, very confused. I've used v-model previously on form inputs with no issues, and have no clue why this is happening or how to fix it. Any thoughts?
const loginInfo = { username, password }toconst loginInfo = { this.username, this.password }and share the results?Syntax error: this is a reserved wordconst loginInfo = { username: this.username, password: this.password }- of course your backend needs to expect an object with this structure.