Answer the question
In order to leave comments, you need to log in
NuxtJS. How to make store.commit in middleware when rendering by server?
Help JS noob plz. NUXT JS middleware code example.
Here is the code (not fully described yet, stuck on the store commit). When rendering on the client, everything works OK, I get the current user, but when rendering on the server it doesn’t work, although the promise returns without an error. Pliz help.
import auth from '../utilites/auth'
import env from '../env'
import axios from 'axios'
export default function ({isServer, store, req, redirect}) {
let token = auth.getToken(isServer, req)
if (!token) {
return redirect('/')
}
let headers = {
Accept: 'application/json',
Authorization: 'Bearer ' + token
}
return axios.get(env.API_DOMAIN + '/user/data', { headers })
.then(({data}) => {
store.state.user = data
})
.catch(() => {
redirect('/login')
})
}
Answer the question
In order to leave comments, you need to log in
I immediately had 2 questions:
1. Why didn't you transfer asynchronous actions to actions?
2. Why do you change the state directly, and not through mutations?
in general, everything was in order, in addition to changing the state directly, and even in this case, the code is working, I messed up in parsing cookies from the request. Inattention is the cause of many mistakes =(
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question