React axios GET null data from Flask backend



我在前端有一个反应表单,用户可以在其中提交他们想问的问题。将表单数据发送到烧瓶服务器,使用一些NLP模型进行计算并获得结果。然后将结果返回到前端。

问题是:我可以看到发布到烧瓶服务器的数据,但是当我尝试从烧瓶服务器获取结果时变为空。

这是前端 QuestionForm 中的 handleSubmit 方法.js:

// post data to flask
axios.post('http://localhost:5000/api/newquestion', this.state)
.then(response => {
    console.log(response)
})
.catch(error => {
    console.log(error)
})

QuestionResult.js中的componentDidMount((方法:

class QuestionResult extends Component {
    constructor() {
        super();
        this.state = {
            questionResult: ''
        }
    }
    componentDidMount() {
        axios.post('http://localhost:5000/api/newquestion')
        .then(response => {
            console.log(response)
            this.setState({questionResult: response.data})
        })
        .catch(error => {
            console.log(error);
        })
    }
    render() {
        const {questionResult} = this.state
        return (
            <div>
                <h1>{questionResult}</h1>
            </div>
        )
    }
}

烧瓶终点(它只是一个测试模型,我现在正在尝试返回问题本身(:

from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/api/newquestion", methods=['GET', 'POST'])
def get_user_question():
    if request.method == 'POST':
        user_question = request.get_json()
        print(user_question)
    return jsonify(user_question)
app.run(port=5000, debug=True)

这是我从python控制台得到的:

127.0.0.1 - - [20/Nov/2019 23:01:12] "OPTIONS /api/newquestion HTTP/1.1" 200 -
None
127.0.0.1 - - [20/Nov/2019 23:01:12] "GET /api/newquestion HTTP/1.1" 200 -
{'question': 'aaaa'}
127.0.0.1 - - [20/Nov/2019 23:01:13] "POST /api/newquestion HTTP/1.1" 200

但是,当我导入另一个函数时 test.py:

def hello():
    return "hi there!"

并将端点更改为:

@app.route("/api/newquestion", methods=['GET', 'POST'])
def get_user_question():
    return hello()

我可以看到消息"你好!"在我的反应页面上成功呈现。

由于 CORS 策略,您不会收到服务器响应。简而言之,默认情况下,浏览器不会允许向与您的页面具有不同端口,协议或域的任何地址发出ajax请求,除非服务器允许通过添加某个响应标头。

在您的情况下,意味着您的 react 应用程序无法与在不同端口上运行的 flask 服务器通信,但您可以对 flask 配置进行一些更改以允许跨源请求。有一些软件包可用于此,例如 https://enable-cors.org/server_flask.html

const config = {
            headers: {'Access-Control-Allow-Origin': '*'}
        };
        axios.post('http://localhost:5000/api/newquestion', this.state, config)
        .then(response => {
            console.log(response)
            this.setState({questionResult: response.data,            isLoaded: true})
        })
        .catch(error => {
            console.log(error)
        })

@app.route("/api/newquestion", methods=['POST'])
@cross_origin(origin='*',headers=['Content-Type'])
def get_user_question():
    data = request.get_json()
    question = data['question']
    result = generate_text(question)
    return jsonify(result)

最新更新