0

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:

flask output in port 8000

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);
      } 
    )
  }, [])

This results in the error: Error Message

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Cin
  • 19
  • 3
  • const [data, setData] = useState([])..l like that it become an array – Naveen Nizam Jul 19 '23 at 06:17
  • 1
    You've set your proxy middleware to only handle requests to `/api/*` but the URL you're requesting doesn't start with `/api` – Phil Jul 19 '23 at 06:25
  • You can debug the code via browser developer tools? of so, put a break point at this line: `response => response.json()` and see what the response is, I guess you got something like 404 (or you were blocked from any reason, so didn't get the correct response from server) – NNH Jul 19 '23 at 07:07

0 Answers0