Answer the question
In order to leave comments, you need to log in
Authentication on the frontend after authorization on the backend. How to implement?
Actually there is this piece of code:
import axios from 'axios'
axios.defaults.withCredentials = true;
export default {
name: 'Home',
data(){
return {
username : "",
password : ""
}
},
methods: {
login(e) {
e.preventDefault();
axios
.post('https://localhost:3011/login', {
username: this.username,
password: this.password,
})
.then(() => {this.$router.push("/")})
.catch(error => console.log(error));
},
Answer the question
In order to leave comments, you need to log in
As an option to make a point to get session data , the GET /auth
back will give data if there is a session or return a 401 error if the user is not authorized. In the vue store, create a user module:
export default {
state: {
user: null,
},
getters: {
isAuthenticated: ({ user }) => Boolean(user),
},
actions: {
getUser({ commit, dispatch }) {
return this.$axios.get('/auth')
.then(user => commit('setUser', user))
.catch(() => dispatch('logout'));
},
login({ dispatch }, { email, password }) {
return this.$axios.post('/login', {
email, password,
})
.then(() => dispatch('getUser'));
},
logout({ commit }) {
commit('unsetUser');
},
},
mutations: {
setUser(state, user) {
state.user = user;
},
unsetUser(state) {
state.user = null;
},
},
};
getUser
, if there is a session, we show something, otherwise, the authorization form, even at the root of the application, you can subscribe to store errors this.$store.subscribeAction
and catch 401 to make a logout
No way. In addition to the option to throw an error from the backend and process it in axios
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question