我是 React 和 Flask API 系统的新手。我创建了一个网站,允许用户通过搜索栏进行搜索。\n我希望能够通过 POST 请求将查询从 React 搜索栏发送到 Flask API。\n但是我得到的是空字符串或 ImmutableDict
\n\n反应代码
\n\nfunction handlePostQuery(query){\n\n if (query != "") {\n axios.post(\'http://localhost:5000/api/query\', query)\n .then(function(response){\n console.log(response);\n //Perform action based on response\n })\n .catch(function(error){\n console.log(error);\n //Perform action based on error\n });\n } else {\n alert("The search query cannot be empty")\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n烧瓶代码
\n\n@app.route(\'/api/query\', methods = [\'POST\'])\ndef get_query_from_react():\n data = request.form\n print(data)\n return data\nRun Code Online (Sandbox Code Playgroud)\n\n按照这个答案:\n获取 Flask 请求中收到的数据
\n\n我尝试了所有这些,但我总是得到(在 Flask 中)一个空字符串,除非我使用request.form它返回类似的内容:
ImmutableMultiDict([(\'what I type in the searchbar\', \'\')])
但是在网络控制台中我得到:
\n\nconfig: {url: "http://localhost:5000/api/query", method: "post", data: "what I type in the search", headers: {\xe2\x80\xa6}, transformRequest: Array(1), \xe2\x80\xa6}\n data: {what I type in the search: ""}\n headers: {content-length: "38", content-type: "application/json"}\n request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: \xc6\x92, \xe2\x80\xa6}\n status: 200\n statusText: "OK"\n __proto__: Object\nRun Code Online (Sandbox Code Playgroud)\n\n我假设 axios 已经从 React 返回了一个 JSON。所以我认为这不是问题。
\n您可以尝试以下操作:
反应
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")
}
}
Run Code Online (Sandbox Code Playgroud)
烧瓶
@app.route('/api/query', methods = ['POST'])
def get_query_from_react():
data = request.get_json()
print(data)
return data
Run Code Online (Sandbox Code Playgroud)
我认为问题是 Axios 没有正确读取 JSON。这就是我创建myParams字典并传递给 Axios 的原因。
| 归档时间: |
|
| 查看次数: |
9031 次 |
| 最近记录: |