【发布时间】: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