How to send a POST request to Flask API using Fetch in a React app

Viewed 3648

To demonstrate my problem, I have made a simple example

    import React, { useEffect } from 'react';

    function App() {
  useEffect(() => {
    fetch('/get')
      .then((response) => response.json())
      .then((data) => console.log(data));
  }, []);

  useEffect(() => {
    fetch('/post', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: 'React POST Request' })
    })
      .then((response) => response.json())
      .then((data) => console.log(data));
  }, []);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: 'React POST Request' })
    })
      .then((response) => response.json())
      .then((data) => console.log(data));
  }, []);

  return <div className="App"></div>;
}

export default App;

In first useEffect hook, I am sending a GET request to my flask API and logging the response of request.

In second useEffect hook, I am sending a POST request to my flask API and logging the response of request.

In thirduseEffect hook, I am sending a POST request to jsonplaceholder.typicode.com/posts and logging the response of request.

first useEffect output: enter image description here

second useEffect output: enter image description here

third useEffect output: enter image description here

I am using the same post request code for request for my Flask API and jsonplaceholder.typicode.com API but response of my API is always empty object {}. Which is not expected. It should return this { title: 'React POST Request' } object. I try to find the solution but nothing work for me.

My simple Flask API:

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


app = Flask(__name__)
CORS(app)

@app.route('/get', methods=['GET'])
def get():
   return { "title": 'React GET Request' }

@app.route('/post', methods=['POST'])
def post():
   return request.args

.flaskenv file:

FLASK_APP=api.py
FLASK_ENV=development

package.json file:

{
  "name": "flask-app-demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.8",
    "@testing-library/react": "^11.2.3",
    "@testing-library/user-event": "^12.6.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5000"
}

By the way, I am using create-react-app package to setup my React App.

1 Answers

That's correct. That's because request.args is exactly that.

https://flask.palletsprojects.com/en/1.1.x/api/?highlight=request%20args#flask.Request.args

The parsed URL parameters (the part in the URL after the question mark).

request.args are querystring parameters, and you are supplying no querystring parameters in your POST.

I'm rusty on flask, but the docs say request.json would return your json encoded post.

https://flask.palletsprojects.com/en/1.1.x/api/?highlight=request%20json#flask.Request.json

Related