通过POST从React到Flask获取数据

时间:2019-10-11 16:26:26

标签: reactjs flask

我是React和Flask API系统的新手。我创建了一个网站,允许用户通过搜索栏进行搜索。 我希望能够通过POST请求将查询从React搜索栏发送到Flask API。 但是我得到一个空字符串或ImmutableDict

反应代码

function handlePostQuery(query){

    if (query != "") {
        axios.post('http://localhost:5000/api/query', query)
            .then(function(response){
                console.log(response);
       //Perform action based on response
        })
        .catch(function(error){
            console.log(error);
       //Perform action based on error
        });
    } else {
        alert("The search query cannot be empty")
    }
}

烧瓶代码

@app.route('/api/query', methods = ['POST'])
def get_query_from_react():
    data = request.form
    print(data)
    return data

遵循以下答案: Get the data received in a Flask request

我尝试了所有方法,但是除非使用request.form,否则我总是会得到一个空字符串(在Flask中),

ImmutableMultiDict([('what I type in the searchbar', '')])

但是我在网络控制台上看到了

config: {url: "http://localhost:5000/api/query", method: "post", data: "what I type in the search", headers: {…}, transformRequest: Array(1), …}
    data: {what I type in the search: ""}
    headers: {content-length: "38", content-type: "application/json"}
    request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
    status: 200
    statusText: "OK"
    __proto__: Object

我假设axios已经从React返回了JSON。所以我认为这不是问题。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

反应

function handlePostQuery(query){

    var myParams = {
        data: query
    }

    if (query != "") {
        axios.post('http://localhost:5000/api/query', myParams)
            .then(function(response){
                console.log(response);
       //Perform action based on response
        })
        .catch(function(error){
            console.log(error);
       //Perform action based on error
        });
    } else {
        alert("The search query cannot be empty")
    }
}

烧瓶

@app.route('/api/query', methods = ['POST'])
def get_query_from_react():
    data = request.get_json()
    print(data)
    return data

我认为问题是Axios无法正确读取JSON。这就是为什么我创建myParams字典并传递给Axios的原因。