我已经设置了一个 flask
rest 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前端。我想做的就是向我的Flask Rest API发出一个GET请求,然后使用console.log输出结果字符串“Hello World”。我遇到了一些CORS问题,所以我添加了这行代码`CORS(app)`,但我仍然有些困扰。
我的fetch请求如下所示...
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 -
我觉得这可能是由于我的请求头中的application/json
导致的。所以我把它删除了...
fetch('http://localhost:5000/', {
method: 'GET',
})
.then(result=>result)
.then(item=>console.log(item))
.catch(e=>{
console.log(e);
return e;
})
OPTIONS
请求已消失,但我的响应仍然相同。我似乎无法将字符串传递到前端。我已经不知道我的问题可能是什么了。