繁体   English   中英

无法从 Django 请求中获取 POST 数据。POST

[英]Cannot get POST data from Django request.POST

我正在尝试验证所需的数据是否包含在 POST 请求中。 我有一个django后端和一个vue3前端。

这是我的 django 视图:

views.py

# Sign user in and issue token
@require_http_methods(['POST'])
def login(request: HttpRequest):
    if request.method == 'POST':
        # check that required fields were send with POST
        print(request.body)
        if {'username', 'password'} >= set(request.POST):  # <- evaluates as False
            print('missing required fields. INCLUDED: ' + str(request.POST))
            return JsonResponse(
                data={'message': 'Please provide all required fields.'},
                content_type='application/json',
                status=400)
        # check that username exists and password matches
        if (User.objects.filter(username=request.POST['username']).count() >
                0):
            user = User.objects.get(username=request.POST['username'])
            if user.password == request.POST['password']:
                # Delete previously issued tokens
                Token.objects.filter(user_id=user.id).delete()
                token = Token(user_id=user.id)
                token.save()
                return JsonResponse(data={'userToken': token.to_json()},
                                    content_type='application/json',
                                    status=200)
        else:
            return JsonResponse(
                data={'message': 'Incorrect username or password.'},
                content_type='application/json',
                status=400)
    else:
        return HttpResponseNotAllowed(permitted_methods=['POST'])

还有我的 axios 请求

Login.vue

axios
  .post('http://localhost:8000/api/users/login', {
    'username': form.get('username'),
    'password': form.get('password'),
  }, {
    validateStatus: (status) => {
      return status !== 500
    },
  })
  .then((response) => {
    console.log(response.data)
    if (response.data.success) {
      // Commit token value to store
      store.commit('setToken', response.data.token)
 
      // Request user data ...

    } else {
      alert.message = response.data.message
      alert.type = 'error'
      document.querySelector('#alert')?.scrollIntoView()
    }
  })

我可以看到在request.POST中设置了usernamepassword ,但没有在request.body中设置,如 django 日志中所示。

December 01, 2021 - 17:40:29
Django version 3.2.9, using settings 'webserver.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
b'{"username":"site.admin","password":"password"}'
missing required fields. INCLUDED: <QueryDict: {}>
Bad Request: /api/users/login
[01/Dec/2021 17:40:30] "POST /api/users/login HTTP/1.1" 400 50
/Users/colby/Projects/emotions/backend/webserver/users/views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

我做错了什么?

编辑

这是从 axios 请求中设置的标头

{
  'Content-Length': '47',
  'Content-Type': 'application/json',
  'Host': 'localhost:8000',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0',
  'Accept': 'application/json,
   text/plain, */*',
  'Accept-Language': 'en-US,en;q=0.5',
  'Accept-Encoding': 'gzip, deflate',
  'Origin': 'http://localhost:8080',
  'Dnt': '1',
  'Connection': 'keep-alive',
  'Referer': 'http://localhost:8080/',
  'Sec-Fetch-Dest': 'empty',
  'Sec-Fetch-Mode': 'cors',
  'Sec-Fetch-Site': 'cross-site',
  'Sec-Gpc': '1'
}

I suspect Axios is setting automatically a content-type: application/json header which means that the request body doesn't contain HTTP POST parameters that can be understood by Django.

您可以通过打印request.headers来验证这一点,如果这确实是问题,请通过以下任一方式解决:

  1. 解析来自 JSON 的请求正文:
import json
data = json.loads(response.body.decode())
if {'username', 'password'} >= set(data):  # etc.
  1. 将数据作为表单数据客户端发送:
var formData = new FormData();
formData.set("username", form.get("username"))
formData.set("password", form.get("password"))
axios
  .post('http://localhost:8000/api/users/login', {
    data: formData,
    headers: {'Content-Type': 'multipart/form-data' }
  })

我个人推荐解决方案 1,因为我发现它不那么冗长且更易于维护,但这主要取决于您的偏好和要求:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM