我试图在 React 中使用 Axios 设置一个简单的帖子表单设置,但由于某种原因它似乎没有作为帖子请求发送,所以 Django 一直抛出 405 错误。
这是调用 axios 并处理表单的 react 代码:
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 登录 View 。我要求它是post,所以当不使用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.")
最佳答案
OPTIONS 请求是飞行前请求。参见 this issue了解更多详情。
您的 View 正在使用 request.POST
,因此希望数据使用 application/x-www-form-urlencoded
而不是 application/json
。如果将 axios 配置为使用 application/x-www-form-urlencoded
,则无需配置 CORS。
如果您确实使用 application/json
,那么您必须配置 CORS。
关于javascript - Axios 不作为 post 方法发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50056897/