django - Axios POST 调用不适用于 JWT 令牌,而 GET 调用有效
问题描述
我正在尝试在 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 后调用中添加更多细节,因为在我将这两件事添加到后调用的标题中后它开始工作:
'Accept' : 'application/json',
'Content-Type': 'application/json'
推荐阅读
- three.js - Three.js:使用 SetTimeOut 在启动后 5 秒对场景中产生的灯光位置进行动画处理
- webpack - 如何在 webpack 解析器中获取文件名?
- email - mymail@mail.com 中的 cat 文件,显示多行(而不是单行)
- java - 使用 Mongodb java driver 3 的 $objectToArray 等价物
- java - 如果他们将字符串放在 int 输入变量上,如何添加 else 语句?
- django - 如何使自定义模板过滤器不区分大小写?(Django 2.1)
- c# - 在 GeckoFx Web 浏览器中查看“dat://”网站
- ruby-on-rails - 如何开发一个用户可以投票给其他用户的投票系统(即类似信誉的系统)?
- arrays - 将 bash 数组分成对,并匹配任一元素
- javascript - ReactJS 中的 Axios Post 调用返回 404 错误