问题
I'm trying to hook up my backend with JWT authentication to a login component in Vue. This is my Vuex action:
userLogin({commit}, payload) {
axios.post('/users/token/obtain/', {
email: payload.email,
password: payload.password,
})
.then(response => {
localStorage.setItem('access', response.data.access)
localStorage.setItem('refresh', response.data.refresh)
let body = JSON.parse(atob(response.data.access.split('.')[1]))
commit('userLogin', {
userToken: response.data.access,
userEmail: body.email,
userFirstName: body.first_name,
userLastName: body.last_name,
userOrganization: body.organization
})
},
error => Promise.reject(new Error(error))
)
}
And the submit method on my login form:
onSubmit() {
const formData = {
email: this.email,
password: this.password,
}
this.$store.dispatch('userLogin', {email: formData.email, password: formData.password}).then(
success => {
console.log(success)
this.$router.push('/dashboard')
},
error => this.errorMessage = error.message
)
}
The problem is that the login form doesn't catch the error if there is one, it always performs the success portion and redirects to /dashboard. It works properly when I enter a correct email and password - the state is updated with the information received in the token.
Am I doing something wrong with regard to promises?
回答1:
this is the way I do it using async ... await:
first declare vuex action as an async function and make it return a value in both success and fail cases like this:
async login({ commit }, payload) {
try {
const response = await axios.post('url', payload);
if (!desiredResponse) throw new Error('some message');
// do something with response
return true;
} catch (e) {
// do something else
return false;
}
}
in the above code any network error goes directly in the catch block which returns false at the end and also if the response does not satisfy some condition i.e. "desiredResponse", it also throws an error and goes into the catch block and returns false. So we can handle both kind of errors here and return false but if there is no error, try block code continues and return true.
now in our component we can use the returned result of that async function like this:
this.$store.dispatch('login', payload).then((res) => {
if (res) {
// do something
} else {
// do something else
}
});
this way we actually use the returned value in our component to decide what to do next.
of course you can return some other values instead of true / false and decide for the next action to take based on them.
来源:https://stackoverflow.com/questions/65343792/vue-login-function