我正在尝试使用Axios在React中设置一个简单的帖子表单,但由于某些原因它似乎没有作为发布请求发送,因此Django不断抛出405错误。
这是调用axios并处理表单的反应代码:
handleSubmit(e) {
console.log('Form state: ', this.state);
e.preventDefault();
const username = this.state.username;
const password = this.state.password;
const formData = {
username: username,
password: password,
}
// Django backend currently running on localhost:8000
axios('http://localhost:8000/login', {
method: 'POST',
data: formData,
}).then(res=> {
console.log('res', res);
console.log('res.data', res.data);
}
)
}
这是django登录视图。我需要发布它,所以当不使用post方法时它会自动抛出405错误。
Django的:
import json, re
from django.shortcuts import get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotFound
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_user
from django.contrib.auth import logout as logout_user
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from api.utils import render
def home(request):
return render(request, 'api/home.html')
@csrf_exempt
@require_http_methods(['POST'])
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
if re.compile('.+@.+\..+').match(username):
user = authenticate(email=username, password=password)
else:
user = authenticate(username=username, password=password)
if user is not None:
auth_user(request, user)
return HttpResponse(json.dumps(True), content_type="application/json")
else:
response = {
'success': False,
'error': True,
'message': "The username/email or password was incorrect.",
}
return HttpResponseForbidden(json.dumps(response))
else:
return HttpResponseForbidden("Post method required.")
答案 0 :(得分:1)
OPTIONS请求是一个飞行前请求。有关详细信息,请参阅this issue。
您的观点正在使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="video-container">
<video autoplay="autoplay" loop="loop" width="100%" height="auto" class="videohome"> Your browser does not support the video tag. <source src="images/video/video.mp4" type="video/mp4" /></video>
<img id="btnplay" class="playbtn" src="images/play.png" alt="Play">
</div>
,因此我们希望数据使用request.POST
代替application/x-www-form-urlencoded
。如果将axios配置为使用application/json
,则不必配置CORS。
如果您使用application/x-www-form-urlencoded
,则必须配置CORS。
答案 1 :(得分:0)
我认为问题与您的应用的Django配置有关。 Axios相关代码似乎是正确的。允许的https动词的示例代码。
class TheView(View):
self.allowed_methods = ['get', 'post', 'put', 'delete', 'options']
def options(self, request, id):
response = HttpResponse()
response['allow'] = ','.join([self.allowed_methods])
return response
您可以检查一次服务器配置吗。