繁体   English   中英

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

[英]How to encode an array and send it via POST request to the backend

我使用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)

输出:

引发 JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

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

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

尝试将其更改为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM