【问题标题】:Axios not sending as post methodAxios 不作为 post 方法发送
【发布时间】:2018-10-07 23:23:03
【问题描述】:

我正在尝试使用 Axios 在 React 中设置一个简单的发布表单,但由于某种原因它似乎没有作为发布请求发送,因此 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 登录视图。我有它需要post,所以它在不使用post方法时会自动抛出405错误。

姜戈:

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.")

【问题讨论】:

    标签: javascript django reactjs axios


    【解决方案1】:

    OPTIONS 请求是飞行前请求。详情请见this issue

    您的视图使用request.POST,因此预计数据使用application/x-www-form-urlencoded 而不是application/json。如果您将 axios 配置为使用 application/x-www-form-urlencoded,那么您将不必配置 CORS。

    如果您确实使用application/json,那么您必须配置 CORS。

    【讨论】:

      【解决方案2】:

      我认为问题与您的应用程序的 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
      

      你能检查一下你的服务器配置吗?

      【讨论】:

      • 如果有帮助,添加 django 视图的完整代码。
      • 也尝试替代反应代码。 axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
      • 我有点困惑。我在哪里把它放在我的views.py 中?我是否只是从该列表中删除任何我不希望方法访问的方法?
      猜你喜欢
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      相关资源
      最近更新 更多