【发布时间】:2021-12-16 11:21:09
【问题描述】:
我在 Flask 上将我的机器学习模型作为 POST 请求提供服务。
我能够在 Postman 中成功发出 POST 请求,但是,在客户端上,尝试在 Next 中获取该端点时收到 CORS 错误。
我有以下 server.py
from flask import Flask, request, jsonify
import pickle
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app)
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
data = request.get_json()
sentence = data['sentence']
vectoriser, LRmodel = load_models()
if vectoriser and LRmodel:
vector = vectoriser.transform([sentence])
prediction = LRmodel.predict(vector)
# return jsonify({'prediction': str(prediction[0])})
if prediction[0] == 1:
return jsonify({'prediction': 'Positive'})
else :
return jsonify({'prediction': 'Negative'})
else:
return jsonify("Error")
return 'Error'
if __name__ == '__main__':
app.run(debug=True)
这是我尝试在客户端调用此端点的方式
const Sentiment = (props: any) => {
return (
<>
<h1 style={{ textAlign: 'center' }}>Sentiment</h1>
<div style={{ textAlign: 'center' }}>
<form action="/sentiment" method="POST" onSubmit={handleSubmit}>
<input type="text" name="sentiment" />
<button type="submit">Submit</button>
</form>
</div>
</>
)
}
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
console.log(e.currentTarget.sentiment.value)
const res = await fetch('http://127.0.0.1:5000/sentiment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sentence: e.currentTarget.sentiment.value }),
})
await res.json()
}
export default Sentiment
我收到此错误: CORS 策略已阻止从源“http://localhost:3000”获取“http://127.0.0.1:5000/sentiment”的访问权限:对预检请求的响应未通过访问控制检查:未通过具有 HTTP ok 状态。
此外,当我提交表单时,我收到“OPTIONS /sentiment HTTP/1.1”404 - 而不是 POST
关于我做错了什么有什么想法吗?
【问题讨论】:
标签: python reactjs flask next.js cors