【问题标题】:How to encode an array and send it via POST request to the backend如何对数组进行编码并通过 POST 请求将其发送到后端
【发布时间】:2019-07-17 01:34:54
【问题描述】:

我在 React.js 前端使用 FileReader 加载 CSV 数据:

import React, { Component } from 'react';
import { CsvToHtmlTable } from 'react-csv-to-table';
import ReactFileReader from 'react-file-reader';
import Button from '@material-ui/core/Button';

const sampleData = `
NUM,WAKE,SIBT,SOBT
1,M,2016-01-01 04:05:00,2016-01-01 14:10:00
2,M,2016-01-01 04:05:00,2016-01-01 14:10:00
3,M,2016-01-01 04:05:00,2016-01-01 14:10:00
`;

class CSVDataTable extends Component {

    state={
      csvData: sampleData
    };

    handleFiles = files => {
        var reader = new FileReader();
        reader.onload =  (e) => {
          // Use reader.result
          this.setState({
            csvData: reader.result
          })
          this.props.setCsvData(reader.result)
        }
        reader.readAsText(files[0]);
    }

    render() {
        return <div>
          <ReactFileReader
            multipleFiles={false}
            fileTypes={[".csv"]}
            handleFiles={this.handleFiles}>
            <Button
                variant="contained"
                color="primary"
            >
                Load data
            </Button>

          </ReactFileReader>
          <CsvToHtmlTable
            data={this.state.csvData || sampleData}
            csvDelimiter=","
            tableClassName="table table-striped table-hover"
          />
    </div>
    }
}

export default CSVDataTable;

然后我应该将csvData 发送到后端。什么是正确的方法?

我尝试发送csvData,但无法在后端正确解析。我假设\n 编码不正确,当csvData 到达后端时:

fetchData = () => {
      const url = "http://localhost:8000/predict?"+
        '&wake='+this.state.wake+
        '&csvData='+JSON.stringify(this.state.csvData);

      fetch(url, {
        method: "POST",
        dataType: "JSON",
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        }
      })
      .then((resp) => {
        return resp.json()
      })
      .then((data) => {
        this.updateDelay(data.prediction)
      })
      .catch((error) => {
        console.log(error, "catch the hoop")
      })
  };

你建议我如何发送csvData?看起来JSON.stringify(this.state.csvData) 做错了什么。请帮我解决这个问题。谢谢。

更新:

我试过了:

  fetchData = () => {
      fetch("http://localhost:8000/predict", {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          wake: this.state.wake,
          csvData: this.state.csvData
        })
      })
      .then((resp) => {
        return resp.json()
      })
      .then((data) => {
        this.updateDelay(data.prediction)
      })
      .catch((error) => {
        console.log(error, "catch the hoop")
      })
  };

但是我无法在 Django 后端(Python)中接收数据:

print(request.POST)

输出:

<QueryDict: {}>

或:

print(request.POST['csvData'])

输出:

django.utils.datastructures.MultiValueDictKeyError: 'csvData'

或者:

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['csvData']

print("content",content)

输出:

从 None 提高 JSONDecodeError("Expecting value", s, err.value) json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(char 0)

【问题讨论】:

  • How do you suggest me to send csvData? : 在正文请求中
  • @samb102:你什么意思?抱歉,我对这些主题很陌生。我给你一个例子或一个网络链接,我将不胜感激。谢谢。
  • 当然,我的错,对不起。只需在fetch 第二个参数的对象中设置body 属性并将JSON.stringify(this.state.csvData) 作为值。见stackoverflow.com/questions/29775797/fetch-post-json-data
  • @samb102:好的,我明白了。但是我应该如何在后端(Python)中从body 检索数据?我试过request.GET.get('csvData'),但没用。
  • 抱歉,我不知道 Python 中的请求是如何处理的。但是看到这个:stackoverflow.com/questions/464040/…

标签: javascript python reactjs


【解决方案1】:

在您的编辑中,您将内容类型设置为 application/json 但在其中发送一个字符串。

body: JSON.stringify({
      wake: this.state.wake,
      csvData: this.state.csvData
})

尝试将其更改为

body: {
   wake: this.state.wake,
   csvData: this.state.csvData
}

【讨论】:

    猜你喜欢
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2017-10-09
    • 2022-10-17
    相关资源
    最近更新 更多