Javascript 如何使用fetch从Flask获取POST数据
我正在使用Flask开发一个推特情绪分析网站。我已经开发了网站的后端 后端代码:Javascript 如何使用fetch从Flask获取POST数据,javascript,python,rest,flask,post,Javascript,Python,Rest,Flask,Post,我正在使用Flask开发一个推特情绪分析网站。我已经开发了网站的后端 后端代码: from flask import * app=Flask(__name__) @app.route('/') def home(): return render_template('tweet.html') @app.route('/result',methods=['GET','POST']) def check_tweet(): if request.method=='POST':
from flask import *
app=Flask(__name__)
@app.route('/')
def home():
return render_template('tweet.html')
@app.route('/result',methods=['GET','POST'])
def check_tweet():
if request.method=='POST':
tweet=request.form['tweet']
result=call_predict_function(tweet) #Returns a dictionary having label and score as keys
return jsonify(tweet=tweet,label=result["label"],score=result["score"])
else:
return render_template('tweet.html')
if __name__ == "__main__":
app.run(debug=True)
我使用请求检查了代码,它按预期工作。我试图在前端接电话。即使显示结果,也不会在控制台中打印数据
前端代码:
<!DOCTYPE html>
<head>
<div class="jumbotron text-center">
<h4>Check Your Tweet</h4>
</div>
</head>
<body>
<div class="container">
<form method="POST" action="http://localhost:5000/result">
<textarea maxlength="300" name="tweet">
</textarea>
<br><br>
<button type="submit" class="btn-dark" onclick="GetResults()">Check</button>
</form>
</div>
<script>
function GetResults()
{
fetch(`${window.origin}/result`,{
method : "POST"
}).then(function(response)
{
if(response.status!=200)
{
console.log(response.statusText);
}
response.json().then(function(data)
{
console.log(data);
});
}).catch(function(error)
{
console.log(error);
});
}
</script>
</body>
</html>
查看你的推文
检查
函数GetResults()
{
获取(`${window.origin}/result`{
方法:“员额”
}).然后(功能(响应)
{
如果(响应状态!=200)
{
console.log(response.statusText);
}
response.json().then(函数(数据)
{
控制台日志(数据);
});
}).catch(函数(错误)
{
console.log(错误);
});
}
我在前端不太好。我哪里出错了?如何从Python获取POST数据?前端的第一个错误:
不包括
或
,它是文档标题的一个部分,即标题、元信息(如字符集、说明、关键字)以及指向样式的链接- 此外,当我们使用表单时,有必要通过JS接管请求的整个解决方案,并抑制默认行为(即从表单中获取数据并转到动作中的url)。或者不要使用提交类型按钮,而是使用
- 另一件事是,缺少要获取的数据附件,您正在向url发送一个POST请求,而没有数据点
- 将标题放入fetch中,至少说明内容是什么(
)内容类型
- 用于标记类型的脚本标记-
应用程序/javascript
查看你的推文
查看你的推文
检查
让tweet=document.queryselectoral(“textarea[name='tweet']”);
函数GetResults()
{
//JSON请求
让fetchJsonRequest={
缓存:“无缓存”,
方法:“张贴”,
标题:{
“内容类型”:“应用程序/json”,
},
正文:{
tweet:tweet.value
},
}
//表单编码的请求,如来自表单的请求
让fetchFormEncodedRequest={
缓存:“无缓存”,
方法:“张贴”,
标题:{
“内容类型”:“应用程序/x-www-form-urlencoded”,
},
正文:新URLSearchParams({
“tweet”:tweet.value,
}),
}
fetch(`${window.origin}/result`,fetchFormEncodedRequest)。然后(函数(响应)
{
如果(响应状态!=200)
{
console.log(response.statusText);
}
response.json().then(函数(数据)
{
控制台日志(数据);
});
}).catch(函数(错误)
{
console.log(错误);
});
}