I have an application running a Flask backend with a React frontend and I'm trying to do some error handling for the front end and display the error message to the user. Here is a simplified version of my files:
Flask
@app.route('/api/download', methods=['POST'])
def download():
data = request.json
#Get data from external API via a post request here
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
print("Success")
data = json.loads(res.decode())
df = pd.json_normalize(data['observationList'])
#Do some pandas magic here
retData = df.to_json(orient="records")
return retData
except Exception as e:
pprint(e)
return jsonify(message='password_update_error'),500
JavaScript
fetch("/api/download", {
method:"POST",
cache: "no-cache",
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify({
values: this.state.values
})
}).then((response) => response.json())
.then(data => {
this.setState({ sdata: data }, () => {
// click the CSVLink component to trigger the CSV download
setTimeout(() => {
this.csvLink.current.link.click();
});
})
}).catch(err => {
errorBox.innerHTML = "<span style='color: red;'>"+
"Could not get data.</span>"
})
This currently gives me two errors:
TypeError: Data should be a "String", "Array of arrays" OR "Array of objects"
TypeError: Cannot read property 'link' of null
I understand what the problem is but I don't know how to return errors so javascript catches it and then displays it in the box like I want it to. Any ideas? Thank you!
At first glance, why don't you just return the error code? It should solve the errors you're getting.
@app.route('/api/download', methods=['POST'])
def download():
data = request.json
#Get data from external API via a post request here
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
print("Success")
data = json.loads(res.decode())
df = pd.json_normalize(data['observationList'])
#Do some pandas magic here
retData = df.to_json(orient="records")
return retData
except Exception as e:
pprint(e)
return 500
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.