I'm trying to get a simple post form setup in React with Axios, but it doesn't seem to be sending as a post request for some reason, so Django keeps throwing a 405 error.
This is the react code that calls axios and handles the form:
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);
}
)
}
This is the django login view. I have it required to be post, so it automatically throws the 405 error when not using post method.
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.")