繁体   English   中英

axios 发布请求未向 django 视图提供任何数据

[英]axios post request not giving any data to django view

我正在尝试使用 axios 向接受 POST 和 GET 的 Django 视图发出我的第一个帖子请求。 我从 request.POST 得到一个空字典:

<QueryDict: {}>
[13/Aug/2022 16:44:00] "POST /users/114260670592402026255 HTTP/1.1" 200 9

服务器确实返回 200 状态代码,但我从 UI 发送的数据不存在。

我有以下 django 视图:

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

import json

from .models import UserProfile

@csrf_exempt
def get_user_profile(request, user_id):
    if request.method == 'GET':
        try:
            user = UserProfile.objects.get(user_id=user_id)
            print("user found")
        except Exception as error:
            print("User profile wasnt found:")
            print(error)
            user = None
            profile = UserProfile()
            profile.user_id = user_id
            profile.searches = [
                {'search_term': 'hd'},
                {'search_term': 'wba'},
            ]
            profile.save()
            print("user saved in db")
            user = UserProfile.objects.get(user_id=user_id)

        data = {
            'user_id': user.user_id,
            'searches': user.searches
        }
        json_data = json.dumps(data)
        return HttpResponse(json_data, content_type='application/json')
    if request.method == 'POST':
        data = request.POST
        print(data)
        return HttpResponse("it worked")

在 UI 应用程序 SearchPage.js 中:

  useEffect(() => {
    console.log("user id changed")
    if (userId) {
      const user_profile_api_url = BASE_URL + '/users/' + userId
      axios.get(user_profile_api_url, {})
        .then(response => {
          const recent_searches_response = response.data.searches;
          const new_recent_searches = [];
          recent_searches_response.map(dict => {
            new_recent_searches.push(dict.search_term)
          })
          setRecentSearches(new_recent_searches);
        })
        .catch((error) => {
          console.log("error in getting user profile: ", error.message)
        })
    }
  }, [userId])

  useEffect(() => {
    const user_profile_api_url = BASE_URL + '/users/' + userId
    const data = {searches: recentSearches}
    // axios.post(user_profile_api_url, {
    //   params: {
    //     searches: recentSearches
    //   }
    // })
    axios.post(user_profile_api_url, data
    })
      .then(response => {
        console.log(response)
      })
  }, [recentSearches])

如您所见,我以正常方式传递它,作为第二个参数,然后我也尝试以 Udemy 课程使用params键的方式传递它。 两者都不起作用。 我怀疑@csrf_exempt可能是导致问题的原因,但我遵循所有在线示例提供的相同格式。 我想从recentSearches视图中的 post 请求中获取最近搜索的数据

发出请求后服务器的响应:

在此处输入图像描述

网络选项卡

在此处输入图像描述

axios 是异步的

你可能会像下面这样打电话

useEffect( async () => {
    const user_profile_api_url = BASE_URL + '/users/' + userId
    const data = {searches: recentSearches}
   const response = await axios.post(user_profile_api_url, data)

console.log(response)
  }, [recentSearches])

更多挖掘导致 http 请求的 Django 文档,我应该从那里开始而不是第三方示例

print(request.body)

数据可以在 django 视图中的 request.body 上找到,并通过加载 Z466DEEC76ECDF2456D38571F63 转换为 python object

b'{"searches":["hd","wba","psec"]}'

暂无
暂无

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

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