I'm very new to react and i'm trying to get a hold on how to properly use fetch. I have this python flask route I'm trying to hit from the back end which looks something like this:
@app.route('/api/v1', methods=['POST'])
def postTest():
if not request.json:
return "not a json post"
return "json post succeeded"
now when I hit this point with post-man I'm actually able to get my successful message.
This is what my reactjs fetch looks like:
returnFlaskPost() {
return fetch( 'http://localhost:5000/api/v1', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: {
'user1':'1234'
}
});
}
I'm very new to react and i'm trying to get a hold on how to properly use fetch. I have this python flask route I'm trying to hit from the back end which looks something like this:
@app.route('/api/v1', methods=['POST'])
def postTest():
if not request.json:
return "not a json post"
return "json post succeeded"
now when I hit this point with post-man I'm actually able to get my successful message.
This is what my reactjs fetch looks like:
returnFlaskPost() {
return fetch( 'http://localhost:5000/api/v1', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: {
'user1':'1234'
}
});
}
Whenever I run my application and attempt to read this function to the console the result I get is this:
Could someone please explain to me what am I doing wrong and what can I do to fix this. I'd greatly appreciate it.
Share Improve this question asked Jan 12, 2019 at 4:10 abefromanabefroman 1491 silver badge6 bronze badges 5- 1 Read message carefully you will get an idea – Just code Commented Jan 12, 2019 at 4:10
- see this S/O for clarification stackoverflow./questions/26980713/… – Chuck LaPress Commented Jan 12, 2019 at 4:15
- Possible duplicate of Solve Cross Origin Resource Sharing with Flask – Alexander Staroselsky Commented Jan 12, 2019 at 4:15
- 3 It's blocked by the browser because of the cross-domain request. You should set up CORS in your flask application. Maybe this would help How to enable CORS in flask and heroku – otong Commented Jan 12, 2019 at 4:23
- did you try adding a proxy that will point to your other localhost in the package.json? – Anthony Commented Jun 12, 2019 at 21:21
1 Answer
Reset to default 8It is a problem of Cross Origin Resource Sharing. In you case you are trying to access the API endpoint from the different URL as the API is being served on itself. By the way, 127.0.0.1:3000 and 127.0.0.1:5000 considered as two different URLs, therefore causing the error that you are referring to. So, to fix this you need to perform the following steps:
Install Flask-CORS:
pip install flask-cors
Include this code in your Flask application (probably __init__.py):
from flask_cors import CORS CORS(app)
That's it!