我用 Django 和 React JS 创建了一个网站。我正在尝试将数组 pict
从我的 JavaScript 前端传递给 Python 后端 Django。
let pict = [];
pictureEl.addEventListener(`click`, function () {
console.log(`Take Pic`);
pict += webcam.snap();
console.log(pict);
});
pict
是相机拍摄的图像数组。我如何将它传递给后端?
答案 0 :(得分:4)
您可以使用 HTTP 请求库(例如 axios、fetch、ajax 请求等)与后端通信
HTTP 通信是通过几个不同的动词(即 GET、POST、PUT、PATCH、DELETE 等)完成的。我不知道您的端点如何处理请求,因此我假设您的端点期望 {{1 }}。 注:
POST
# 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)
}
答案 1 :(得分:0)
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' 关键字一样访问这些数据