First, when not sure authorization token is the real problem or not. when using passport and giving token for the auth. There is no problem with that part. User can register, login or logout. Also logged in user seeing pages only auth user can see. But when it comes to like or dislike an article. This error popping up. Route [login] not defined. it seems like in my controller below. this part is not working properly. Auth::user()->id
public function postLikeArticle( $id ){
$article = Article::where(‘id’, ‘=’, $id)->first();
if( !$article->likes->contains( Auth::user()->id ) ){
$article->likes()->attach( Auth::user()->id, [
‘created_at’ => date(‘Y-m-d H:i:s’),
‘updated_at’ => date(‘Y-m-d H:i:s’)
] );
}
return response()->json( [‘article_liked’ => true], 201 );
}
When I like the post when having 401 (Unauthorized) and my request header is looks like below.
No authorization token in the request header. And this makes me think that when doing something wrong at login part in my vuex. Which is like below.
export const articles = {
state: {
token: localStorage.getItem(‘access_token’) || null,
},
getters: {
loggedIn(state){
return state.token !== null;
}
},
mutations: {
fetchToken(state, token) {
state.token = token
},
},
actions: {
fetchToken(context, credentials){
return new Promise((resolve, reject) => {
axios.post(“/api/v1/login”, {
username:credentials.username,
password:credentials.password,
})
.then(response => {
const token = response.data.access_token
localStorage.setItem(‘access_token’, token)
context.commit(“fetchToken”, token)
resolve(response)
axios.defaults.headers.common[‘Authorization’] = ‘Bearer ‘ + context.state.token
})
.catch(error => {
console.log(error)
reject(error)
})
})
},
},
}
when not sure what when doing wrong. but it seems Auth:: is doesn’t know user logged in… When I logged in at first authorization token is there. But when I refresh the page it’s gone.
Solution :
Also logged in user seeing pages only auth user can see.
How are you doing this? If the user can see what auth user can see, which means you are making GET request with auth token right? If you’re using a passport, you should put the token into the Authorization header.
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
Use this to put the token into the all axios request after you have login, then you should be good to go.