如何从Flask返回错误,以便JavaScript捕获它

2024-04-24 23:56:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个运行Flask后端和React前端的应用程序,我正在尝试对前端进行一些错误处理,并向用户显示错误消息。以下是我的文件的简化版本:

烧瓶

@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>"
        })

这目前给了我两个错误:

TypeError: Data should be a "String", "Array of arrays" OR "Array of objects" 
TypeError: Cannot read property 'link' of null

我知道问题是什么,但我不知道如何返回错误,所以javascript会捕获错误,然后像我希望的那样将其显示在框中。有什么想法吗?谢谢大家!


1条回答
网友
1楼 · 发布于 2024-04-24 23:56:14

乍一看,为什么不直接返回错误代码呢?它应该能解决你所遇到的错误

@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

相关问题 更多 >