7

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:

enter image description here

Could someone please explain to me what am I doing wrong and what can I do to fix this. I'd greatly appreciate it.

abefroman
  • 139
  • 1
  • 6
  • 1
    Read message carefully you will get an idea – Just code Jan 12 '19 at 04:10
  • see this S/O for clarification https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask – Chuck LaPress Jan 12 '19 at 04:15
  • Possible duplicate of [Solve Cross Origin Resource Sharing with Flask](https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask) – Alexander Staroselsky Jan 12 '19 at 04:15
  • 3
    It's blocked by the browser because of the cross-domain request. You should set up [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) in your flask application. Maybe this would help [How to enable CORS in flask and heroku](https://stackoverflow.com/questions/25594893/how-to-enable-cors-in-flask-and-heroku) – otong Jan 12 '19 at 04:23
  • did you try adding a proxy that will point to your other localhost in the package.json? – Anthony Jun 12 '19 at 21:21

1 Answers1

7

It 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:

  1. Install Flask-CORS:

    pip install flask-cors
    
  2. Include this code in your Flask application (probably __init__.py):

    from flask_cors import CORS
    CORS(app)
    

That's it!

none32
  • 515
  • 1
  • 5
  • 21