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?
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'])