烧瓶和反应的 Hello World 示例

Hello World example with flask and react

我已经设置了 flask 休息 API 是这样的:

from flask import Flask
from flask import jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route('/', methods=['GET'])
def hello_world():
   return "Hello World"

if __name__ == '__main__':
   app.run()

现在,我还设置了一个 React front-end。我想要做的就是向我的 flask rest API 和 console.log 发出 GET 请求,结果字符串 Hello World". I had someCORSissues so I added the lineCORS(app )`,但是我仍然遇到了一些问题。

我的提取请求看起来是这样...

componentDidMount() {

    fetch('http://localhost:5000/', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
      .then(result=>result)
      .then(item=>console.log(item))
      .catch(e=>{
        console.log(e);
        return e;
      })
}

我得到的结果如下...

Response { type: "cors", url: "http://localhost:5000/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false } App.js:24

没有我的 Hello World 字符串的迹象。我还注意到我的服务器正在发出 OPTIONS 请求...

127.0.0.1 - - [26/Jul/2018 14:13:54] "OPTIONS / HTTP/1.1" 200 -
127.0.0.1 - - [26/Jul/2018 14:13:54] "GET / HTTP/1.1" 200 -

我决定这可能会对 headers 中的 application/json 造成影响。所以我删除了它...

fetch('http://localhost:5000/', {
  method: 'GET',
})
  .then(result=>result)
  .then(item=>console.log(item))
  .catch(e=>{
    console.log(e);
    return e;
  })

OPTIONS请求消失了,但我的回复还是一样。

我似乎无法获取 front-end 的字符串。我不知道我的问题可能是什么了。

您可以使用 jsonify 到 return 响应对象,而不是 return 从您的 Flask 路由中获取字符串:

return jsonify({"data": "Hello World"})

然后在 React 中,您可以在响应中调用 json 方法来获取包含数据的 JavaScript 对象:

.then(result=>result.json())  // instead of .then(result=>result)

然后您应该会看到控制台中记录了以下内容:

{data: "Hello World"}