M
M
Mike2018-04-05 21:45:22
Django
Mike, 2018-04-05 21:45:22

Why can't I log in until I do CTRL + F5?

The main page has three links "Home" "Blog" and "Sign in" and a logout button.
The "Blog" link only works for an authorized user. Here it is:
app/views.py

from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated 
from . models import Post
from . serializers import PostSerializer

class PostViewset(viewsets.ModelViewSet):

    permission_classes = (IsAuthenticated,) # только для авторизованного юзера
    queryset = Post.objects.all()
    serializer_class = PostSerializer

In vue.js, I log in and get a token (JWT) and store it in localsorage. Here is login.vue:
<script>
import axios from 'axios'
export default {
    name: 'login',
    data() {
        return {
            endpoint: 'http://localhost:8000/rest-auth/login/',
            username: '',
            password: ''
        }
    },
    methods: {
        login() {
            axios.post(this.endpoint, {username:  username, password: this.password})
            .then(response => {
                const token = response.data.token
                localStorage.setItem('user-token', token)
                console.log(response)
                this.$router.push({name: 'home'})
            })
        }
    }
}
</script>

And in the component where all the posts of my "Blog". I am passing the token like this:
<script>

import axios from 'axios'

export default {
    name: "Blog",
    data() {
        return {
            endpoint: 'http://localhost:8000/api/app/',
            posts: []
        };
    },
    methods: {
        getAllPosts() {
            axios.defaults.headers.common['Authorization'] = 'JWT ' + localStorage.getItem('user-token');
             axios.get(this.endpoint).then(Response => {
                 this.posts = Response.data
            })
        }
    },
    created() {
        this.getAllPosts()
    }
};
</script>

It all works, an authorized user can read posts, you can also log out and log back in. But there's a problem. When a user clicks on the logout button (logs out) and tries to follow the "Blog" link (only for an authorized user) in the browser console, I get "GET localhost: 8000/rest-auth/login 401 (Unauthorized)", in principle, this is normal , so it should be. Now, if I try to log in, I get POST localhost:8000/rest-auth/login 401 (Unauthorized) until I press "ctrl + f5" and only then can I successfully log in. If after logout you do not click on the "Blog" link, but follow the "Home" link where there are no restrictions and then try to log in, then everything turns out great and even without "ctrl + f5.
If you rewrite the "Blog" component a little bit, namely the getAllPosts() function in this way:
axios.get(this.endpoint, {headers: {'Authorization': 'JWT ' + localStorage.getItem('user-token')}}).then(Response => {
                 this.posts = Response.data
             })

then the problem disappears.
How can I correctly pass the token so that I do not write every time in the headers of this.?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
levchak0910, 2018-04-06
@google_online

Let me introduce you to spoilers )
In your case

axios.interceptors.request.use(function (config) {
    const userToken = localStorage.getItem('user-token');
    if(userToken) config.headers["Authorization"] = `JWT ${userToken}`;
    return config;
});

Use vue-axios to avoid having to import axios every time

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question