【问题标题】:Django ReactJS: Pass array from JavaScript frontend to Django Python backendDjango ReactJS:将数组从 JavaScript 前端传递到 Django Python 后端
【发布时间】:2021-06-25 08:36:46
【问题描述】:

我用 Django 和 React JS 制作了一个网站。我正在尝试将数组 pict 从我的 JavaScript 前端传递给 Python 后端 Django。

let pict = [];

pictureEl.addEventListener(`click`, function () {
  console.log(`Take Pic`);
  pict += webcam.snap();
  console.log(pict);
});

pict 是相机拍摄的图像数组。我如何将它传递给后端?

【问题讨论】:

    标签: javascript python reactjs django


    【解决方案1】:

    您可以使用 HTTP 请求库(例如 axios、fetch、ajax 请求等)与您的后端通信

    HTTP 上的通信是通过几个不同的动词(即 GET、POST、PUT、PATCH、DELETE 等)完成的. 注意:

    • 下面的例子使用axios作为JS的HTTP请求库
    • 我建议更改您的原始代码以使用图片
    # urls.py
    from django.urls import path
    
    from . import views
    
    url_patterns = [
      path('path/to/my_endpoint', views.my_endpoint),
    ]
    
    # views.py
    from django.http import HttpResponse
    
    def my_endpoint(request):
        pict = request.POST.getlist('pict[]')
        process_pict(pict)
        return HttpResponse('Success')
    

    在这种情况下,您可以将请求发送到您的服务器,如下所示:

    // api.js
    import axios from 'axios'
    
    export function sendPict(pict) {
      const payload = {'pict[]': pict}
      return axios.post('path/to/my_endpoint', payload)
    }
    

    然后您可以从您的应用中将您的图片发送到任何地方:

    import sendPict from './api'
    const pict = [];
    pictureEl.addEventListener(`click`, function () {
      console.log(`Take Pic`);
      pict.push(webcam.snap());
      console.log(pict);
      console.log('sending pict to server')
      sendPict(pict)
        .then(response => console.log(`The success server response is: ${response}`))
        .catch(error => alert(`Oh noes: ${error}`))
    });
    

    【讨论】:

    • 感谢您的详细回复。虽然我还是有点糊涂。你能给我一个axios.post('path/to/my_endpoint', payload) 的示例路径吗?
    • 当然,我编辑了上面的答案以包含一个 sn-p,它将 django 视图(my_endpoint)添加到将为其提供服务的 url。 - Django 视图参考:docs.djangoproject.com/en/3.2/topics/http/views - Django 网址参考:docs.djangoproject.com/en/3.2/topics/http/urls
    • 非常感谢。虽然我收到了Forbidden (CSRF token missing or incorrect.): /path/to/my_endpoint 错误,所以我在my_endpoint 函数上方添加了@csrf_exempt。它修复了错误,但现在当我 print(pict) 我得到一个空列表。
    • 确保: 1. 在后端和前端使用您在前端使用的相同密钥(例如pict[]) 2. 您从后端发送的值与您收到的相同在后端。您可以通过查看浏览器控制台的网络选项卡并打印 request.POST 来执行此操作
    • 嗨,卡洛斯。这实际上是因为我没有在views.py 中正确加载数据。它应该是data = json.loads(request.body)pict = data['pict[]']。感谢您的帮助!
    【解决方案2】:
        import React from 'react'
        import axios from 'axios'
        
        postPict = (pict) => {
    
            //data is a json object which will have your pict array set to 'data' keyword
            
            const data= {'data': pict}
    
            //the next line would return a promise to 'http://localhost:8000' with the data object defined above
    
            return axios.post('http://localhost:8000', data)
        }
        
        pictureEl.addEventListener(`click`, function () {
            console.log(`Take Pic`);
            pict += webcam.snap();
            console.log(pict);
    
    //here you call the function defined as postPic to access the promise and add the necessary code in the respective blocks of then(will contain success condition codes) and catch(will contain error condition codes)
    
            postPic(pict)
                .then(res => {
                    console.log(res)
                    //Do whatever you want
                })
                .catch(err => {
                    console.log(err)
                    //Do whatever you want
                })
        
        });
    

    您可以像访问 Django 中的 json 数据以及 'data' 关键字一样访问这些数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2018-12-19
      • 2011-10-24
      相关资源
      最近更新 更多