I'm trying to build REST API in Django which I connect with Vue.js on the front end by using the axios library with using the JWT token authentication.
However when I make POST Django says Unauthorized, while when I use GET everything seems to work correctly.
Both POST and GET are defined as part of the same class and I use permission_classes = (IsAuthenticated,) to check for permissions.
Backend class:
from django.shortcuts import render
# Generic API views
from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.models import User
from api.models import Movie
from api.models import WatchList
from api.serializers import WatchListSerializer
from api.add_movie import add_movie
class WatchListAPI(generics.GenericAPIView):
"""
"""
permission_classes = (IsAuthenticated,)
def get(self, request):
"Returns all the movies in personal watch list"
current_user = request.user
current_watchlist = WatchList.objects.filter(user=current_user).prefetch_related('movie')
serializer = WatchListSerializer(current_watchlist, many=True)
return Response(serializer.data)
def post(self, request):
current_user = request.user
new_movie_id = request.data['movie_id']
# In case we don't have current movie in our database
add_movie(new_movie_id)
current_movie = Movie.objects.get(movie_id=new_movie_id)
new_watchlist_element = WatchList(
user=current_user,
movie=current_movie
)
if(WatchList.objects.filter(user=current_user, movie=current_movie).count() != 0):
return Response({"error": "that movie is already present in the watchlist"})
new_watchlist_element.save()
return Response({"message": "added new movie"})
Front end call which work:
axios.get('http://localhost:8000/watchlist/', {
headers: {
Authorization: "Bearer " + currentToken.access
}
}).then(
data => {
this.watchList = [];
for(let i=0;i<data.data.length;i++) {
this.watchList.push({
movieTitle: data.data[i]['movie']['movie_name'],
shortSummary: data.data[i]['movie']['overview'],
yearProduction: data.data[i]['movie']['production_year'],
moviePoster: data.data[i]['movie']['poster_path'],
rating: 5,
});
}
}
);
Front end call which doesn't work:
axios.post('http://localhost:8000/watchlist/', {
headers: {
Authorization: "Bearer " + currentToken.access
},
movie_id: this.movieSearchQueue[i]['movieId'],
}).then(data=>console.log(data));