我有一个使用python Flask的后端和一个使用react的前端。 Python后端如下,
from flask import Flask, request, jsonify
from sklearn.externals import joblib
from flask_cors import CORS, cross_origin
HOST = "0.0.0.0"
PORT = 8080
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/')
@cross_origin()
def root():
return '<h1>top level</h1>'
@app.route('/api/predict', methods=['GET', 'POST'])
@cross_origin()
def predict():
print(request)
request_data = request.json
input_text = request_data['input']
vectorizer = joblib.load('vectorizer.pkl')
classifier = joblib.load('model.pkl')
tokenized_input = vectorizer.transform([input_text])
prediction_rbf = classifier.predict(tokenized_input)
priediction_proba = classifier.predict_proba(tokenized_input)
probabilities = zip(classifier.classes_, priediction_proba[0]) #shows all propabilities
response = {k:v for k,v in probabilities}
response['feeling'] = prediction_rbf[0]
return jsonify({'response':response})
if __name__ == "__main__":
app.run(host=HOST, port=PORT, debug=True)
React前端如下,
import React, { Component } from 'react'
import {Radar} from 'react-chartjs';
const propTypes = {}
const defaultProps = {}
class EmotionDecectionView extends Component {
constructor(props) {
super(props)
this.state = {
hasResponse:false,
response:{
disgust: 0,
fear: 5,
feeling: "",
happiness: 10,
neutral: 0,
sadness: 0,
surprise: 0
}
}
this.inputTextSubmit = this.inputTextSubmit.bind(this);
this.chartRef = React.createRef();
}
inputTextSubmit(event){
if(event.key === 'Enter'){
let inputText = event.target.value
fetch('http://localhost:8080/api/predict', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'input':inputText})
})
.then(res => res.json())
.then(res => {
this.setState({
hasResponse:true,
response:{
disgust: res.response.disgust,
fear: res.response.fear,
feeling: res.response.feeling,
happiness: res.response.happiness,
neutral: res.response.neutral,
sadness: res.response.sadness,
surprise: res.response.surprise
}
})
window.scrollTo(0, window.innerHeight.offsetTop)
})
}
}
render() {
return (
<div>
<main className="main-content">
<div className="fullwidth-block">
<div className="container">
<h2 className="section-title">Try Lexis</h2>
<small className="section-subtitle">Just type something in the textarea</small>
<textarea onKeyPress={this.inputTextSubmit} className="figure" placeholder="Some example text here"></textarea>
</div>
</div>
{this.state.hasResponse &&
<div className="fullwidth-block">
<div className="container">
<h2 className="section-title">Emotions in the text</h2>
<small className="section-subtitle">We can detect multiple types of emotion</small>
<Radar ref={this.chartRef} redraw data={{
labels:['disgust', 'fear', 'happiness', 'neutral', 'sadness', 'surprise'],
datasets:[
{
label:"Emotion",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [
this.state.response.disgust,
this.state.response.fear,
this.state.response.happiness,
this.state.response.neutral,
this.state.response.sadness,
this.state.response.surprise
]
}
]}
} options={{responsive: true,
maintainAspectRatio: true,}} />
</div>
</div> }
</main>
</div>
)
}
}
EmotionDecectionView.propTypes = propTypes
EmotionDecectionView.defaultProps = defaultProps
export default EmotionDecectionView
我尝试使用chrome并将chrome扩展添加到Moesif CORS以处理cors,但是在控制台中仍然出现错误,如下图所示。
我尝试了互联网上的所有内容,但没有任何工作对我有用。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
您的服务器和客户端使用相同的来源,这就是为什么出现此错误的原因
将此添加到您的请求标头Access-Control-Allow-Origin: *