javascript - Axios 不作为 post 方法发送

标签 javascript django reactjs axios

我试图在 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/

相关文章:

javascript - 从嵌套数组中获取数据

javascript - 我可以在不检查 jQuery 是否已完全加载的情况下构建 jQuery 原型(prototype)函数吗?

javascript - 在类组件中使用react-i18next

javascript - 搜索引擎索引如何为 JavaScript Web 应用程序(如 REACT)工作?

reactjs - 使用 create-react-app 时未创建 public、src 和 script 文件夹

javascript - 为什么我不能让 bootstrap popover 工作?

javascript - 如何将自定义属性添加到 javascript 中的自定义构造函数?

Django/python : 'function' object has no attribute 'as_view'

python - 如何处理 'dict' 对象没有属性 'META' ?

python - 基于 Django 类的 View 登录