如何编码数组并通过POST请求将其发送到后端

时间:2019-02-22 22:07:45

标签: javascript python reactjs

我使用FileReader在React.js前端加载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(“期望值”,s,err.value)   json.decoder.JSONDecodeError:预期值:第1行第1列(字符   0)

0 个答案:

没有答案