【发布时间】:2021-05-31 06:51:23
【问题描述】:
我正在尝试在 Django 中构建 REST API,我通过使用 axios 库和 JWT 令牌身份验证在前端与 Vue.js 连接。
但是,当我进行 POST 时,Django 显示未经授权,而当我使用 GET 时,一切似乎都正常工作。
POST 和 GET 都被定义为同一个类的一部分,我使用 permission_classes = (IsAuthenticated,) 来检查权限。
后端类:
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"})
有效的前端调用:
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,
});
}
}
);
前端调用不起作用:
axios.post('http://localhost:8000/watchlist/', {
headers: {
Authorization: "Bearer " + currentToken.access
},
movie_id: this.movieSearchQueue[i]['movieId'],
}).then(data=>console.log(data));
【问题讨论】:
-
你需要给我们看一些代码
-
我刚刚添加了代码,axios.get 有效,而 axios.post 无效
-
我可以看看你的 REST_FRAMEWORK 设置吗?
-
我已经在那里配置了 CORS_HEADERS,我在 axios post call 中添加了这两件事,现在它似乎可以工作了:'Accept' : 'application/json', 'Content-Type': 'application /json'
-
很高兴听到这个消息,那么也许您可以用可行的解决方案回答您的问题并接受它,以便其他人可以轻松找到它