Django无法得到POST请求的参数?

在使用axios向后端发送POST请求的时候,服务器无法得到POST中带有的参数。
前端的发送代码如下:

Http({
    method:'POST',
    url:'signup',
    data:{
        username:this.signUpform.username,
        password:this.signUpform.password,
        email:this.signUpform.email,
        cellphone:this.signUpform.cellphone
    }
})

Axios设置如下:

import axios from 'axios'
export default axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 20000,
  headers: {'Content-Type': 'application/json'}
})

后台接受代码如下:

@require_http_methods(["POST"])
def signup(request):
    response = {}
    try:
        print(request.POST.get('username'))
        WorkUser.objects.get(username=request.POST.get('username'))
        response['error'] = 'username already exist'
    except WorkUser.DoesNotExist:
        wu=tools.toWorkUser(request)
        wu.save()
        response['error'] = 'success'
        
    return JsonResponse(response)

输出,显示:

None
Internal Server Error: /api/signup
Traceback (most recent call last):
  File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 77, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'username'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\http.py", line 40, in inner
    return func(request, *args, **kwargs)
  File "E:\WorkSpace\GraduationThesis\GPServer\server\views.py", line 36, in signup
    WorkUser.objects.get(username=request.POST['username'])
  File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 79, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'username'

然而,使用Postman接口却可以使用,这是为什么呢

阅读 3.6k
评论
    4 个回答

    终于找到可以用的办法了,似乎只要在前端对data处理一下就可以了,用qs:

    data:qs.stringify({
            'username':this.signUpform.username,
            'password':this.signUpform.password,
            'email':this.signUpform.email,
            'cellphone':this.signUpform.cellphone
    })
      • 72

      建议用postman先测试下接口

        • 2.2k

        后端,你打印一下:request.body,看看你的参数是不是在里面。

          • 11.2k

          axios使用axios.post(url, params)的方式调用更合适

            撰写回答

            登录后参与交流、获取后续更新提醒