1

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));
5
  • You need to show us some code Commented Mar 1, 2021 at 18:51
  • I have just added code, the axios.get works while axios.post doesn't Commented Mar 1, 2021 at 18:55
  • Can I see your REST_FRAMEWORK settings, please? Commented Mar 1, 2021 at 19:12
  • I have configured the CORS_HEADERS there, I added those two things in the axios post call and it seems to work now: 'Accept' : 'application/json', 'Content-Type': 'application/json' Commented Mar 1, 2021 at 19:30
  • Good to hear, then perhaps, you may answer you question with the working solution and accept it so other people may find it easily Commented Mar 1, 2021 at 19:39

1 Answer 1

1

It seems like I should've added more details into the Axios post call, as it started working after I added those two things into the headers of the post call:

'Accept' : 'application/json', 
'Content-Type': 'application/json'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.