Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send POST data to flask using Reactjs fetch

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.

like image 723
abefroman Avatar asked Jan 12 '19 04:01

abefroman


People also ask

How do I send a POST request in React?

One is the URL, while the second contains options like the request method ( POST ), body , which is the info we are posting (must be stringified), and then the headers : handleSubmit = (e) => { e. preventDefault(); fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.


1 Answers

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!

like image 102
none32 Avatar answered Sep 18 '22 02:09

none32