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.
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.