This is my first time connecting Flask to React. I am trying to fetch the information from my flask API to use for my React frontend but get Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. The information being fetched is from mysql. Flask server.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import products_dao
from sql_connection import get_mysql_connection
app = Flask(__name__)
CORS(app)
connection = get_mysql_connection()
@app.route('/api/getProducts', methods=['GET'])
def get_products():
response = products_dao.get_all_products(connection)
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin', '*')
return response
if __name__ == "__main__":
app.run(port=8080, debug=True)
This results in http://localhost:8080/api/getProducts:
The React code is:
import { useState, useEffect } from "react";
const MainPage = () => {
const [data, setData] = useState([{}])
useEffect(() => {
fetch("/getProducts").then(
response => response.json()
).then(
responseJson => {
setData(responseJson)
console.log(responseJson);
}
)
}, [])
I do know this error is caused if the data being sent is an HTML and not a JSON but I do not know why it results in this error because server.py jsonify() the data and returns it. I have added a proxy with a setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
createProxyMiddleware('/api',{
target: 'http://localhost:8080',
changeOrigin: true,
})
);
};
The result I would like is the Flask API result in the console.