React调用Flask时为什么会出现CORS问题,尽管已包含flask_cors?

huangapple go评论76阅读模式
英文:

Why does React to Flask call fail with CORS despite flask_cors being included

问题

你可以在Flask应用中添加适当的CORS(跨源资源共享)头,以解决这个问题。在你的Flask应用中的代码中,你已经使用了Flask-CORS来处理跨域请求,但似乎还需要进一步配置。请尝试以下步骤:

  1. 确保你已经安装了Flask-CORS库。

  2. 在应用中的CORS配置中,指定允许的源(origin)。在你的代码中,允许的源是'http://localhost:3000'。确保这个值是正确的。

  3. 添加Access-Control-Allow-Origin头,将其设置为允许的源,这样浏览器就会允许跨域请求。在你的process_data函数中,添加如下代码:

response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')

你的process_data函数应该像这样:

@app.route('/api/data', methods=['POST'])
def process_data():
    data = request.get_json()
    # 处理数据
    response_data = {'message': 'Success'}
    response = jsonify(response_data)
    response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
    return response, 200

这样应该解决CORS问题,并允许你的React应用从Flask应用读取数据。

英文:

I need to read data from flask into react.
React:

const data = {
        name: 'John',
        email: 'john@example.com'
    };

    axios.post('http://127.0.0.1:5000/api/data', data)
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.log(error);
        });

Flask:

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

app = Flask(__name__)
CORS(app, origins='http://localhost:3000')

@app.route('/api/data', methods=['POST'])
def process_data():
    data = request.get_json()
    # обработка данных
    response_data = {'message': 'Sucsess'}
    return jsonify(response_data), 200


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


And i take in browser an error: Access to XMLHttpRequest at 'http://127.0.0.1:5000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ShortPage.jsx:24 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

How can i fix this?

答案1

得分: 1

The problem is that you are limiting the path /api/data to the http method POST

问题在于您将路径/api/data限制为HTTP方法POST

@app.route('/api/data', methods=['POST'])

@ app.route('/ api / data',方法= ['POST'])

CORS requires the client to make an OPTIONS 'pre-flight' call on that path to find out which origins are allowed (and other stuff like headers). Because your code only permits POST the OPTIONS call is declined and the CORS mechanism fails.

CORS需要客户端在该路径上进行“预检”调用以查找允许的来源(以及其他内容,如标头)。由于您的代码仅允许POST,因此OPTIONS调用被拒绝,CORS机制失败。

The fix is to add the OPTIONS to the list of permitted methods on the route.

解决方法是将OPTIONS添加到路由上允许的方法列表中。

@app.route('/api/data', methods=['POST', 'OPTIONS'])

@ app.route('/ api / data',方法= ['POST','OPTIONS'])

英文:

The problem is that you are limiting the path /api/data to the http method POST

@app.route('/api/data', methods=['POST'])

CORS requires the client to make an OPTIONS 'pre-flight' call on that path to find out which origins are allowed (and other stuff like headers). Because your code only permits POST the OPTIONS call is declined and the CORS mechanism fails.

The fix is to add the OPTIONS to the list of permitted methods on the route.

@app.route('/api/data', methods=['POST', 'OPTIONS'])

huangapple
  • 本文由 发表于 2023年4月20日 01:22:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定