从React向Flask服务器发出Fetch/Axios请求时出现网络错误

aamkag61  于 12个月前  发布在  iOS
关注(0)|答案(2)|浏览(145)

我在从React应用程序向Flask服务器发出网络请求时遇到了一个问题。令人惊讶的是,Flask服务器成功接收了请求,但当我试图返回响应时,我总是在客户端收到一个“网络错误”。当使用fetchaxios发出简单的GET请求时,就会出现这种情况。
详细信息:

服务器设置:

确认我的Flask服务器在http://127.0.0.1:8000上运行。CORS使用flask_cors配置。即使在异常的情况下,服务器也会返回200状态代码。代码:

@app.route('/test', methods=['GET'])
def test():
    delete_db(["***"])
    try:
        for data in array:
            suppliers = build_supliers(data)
            for supplier in suppliers:
                insert_supplier(suppliers[supplier])
        
        logger.info('All suppliers have been inserted successfully');
        return jsonify({"data":None, "status":200, "message": "successfully"})
    except Exception as e:
        logger.error(f"An error occurred during synchronization: {str(e)}")
        return jsonify({"error": str(e), "status": 500, "message": "Internal Server Error"})

字符串

客户代码:

对GET请求使用fetch或axios。头部设置正确('Accept':'application/json,text/plain,*/xml')。
代码:

export const test = async (): Promise<any>=> {
  try {
    const response = await axios.get(`${process.env.REACT_APP_SYNC_SERVER}/test`,{ headers: {
    "Accept": "application/json, text/plain, */*",
  },});
    return response.data;
  } catch (error:any) {
    const { data } = error.response;
    throw data;
  }
};

尝试解决:

1.已验证服务器可访问性。

  1. CORS配置。
    1.已检查浏览器控制台以了解其他错误详细信息。
    1.已尝试使用fetch执行相同的请求。
    有人在React应用和Flask服务器之间进行网络请求时遇到过类似的问题吗?Flask成功接收了请求,但在尝试返回响应时出现了“网络错误”。有关于如何解决或解决此问题的建议吗?
    错误对象:
{
    "message": "Network Error",
    "name": "AxiosError",
    "stack": "AxiosError: Network Error\n    at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:819713:14)",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "adapter": [
            "xhr",
            "http"
        ],
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {},
        "headers": {
            "Accept": "application/json, text/plain, */*"
        },
        "method": "get",
        "url": "http://localhost:8000/test"
    },
    "code": "ERR_NETWORK",
    "status": null
}

wko9yo5t

wko9yo5t1#

仔细检查您是否正确使用CORS,它会完成这项工作。

from flask_cors import CORS
from flask import Flask, jsonify

# Start script
app = Flask(__name__)
CORS(app) # ADD This line.

@app.route('/test', methods=['GET'])
def test():
    delete_db(["***"])
    try:
        for data in array:
            suppliers = build_supliers(data)
            for supplier in suppliers:
                insert_supplier(suppliers[supplier])
        
        logger.info('All suppliers have been inserted successfully');
        return jsonify({"data":None, "status":200, "message": "successfully"})
    except Exception as e:
        logger.error(f"An error occurred during synchronization: {str(e)}")
        return jsonify({"error": str(e), "status": 500, "message": "Internal Server Error"})

字符串

h79rfbju

h79rfbju2#

你可以尝试reuqqs从 Postman 结束点,并看到响应和状态代码,没有代码无法重现错误。

相关问题