Answer the question
In order to leave comments, you need to log in
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
<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>
<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>
axios.get(this.endpoint, {headers: {'Authorization': 'JWT ' + localStorage.getItem('user-token')}}).then(Response => {
this.posts = Response.data
})
Answer the question
In order to leave comments, you need to log in
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;
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question