簡體   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