0

I am new to React.js and Flask and am creating a basic app following an outdated tutorial. My github repo is: https://github.com/CadeHarger/flaskdemo. I am in the process of establishing a frontend-backend connection. After starting the server by running api.py, and then starting the react app with npm start, I get the following browser console error: (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. This resulted in the object that I wanted to send from the backend to the front not going through when I try to print it to the console. In my VSCode that I am using to run both sides, I get no errors printed in the terminal. The object is being properly returned by the server after checking localhost:5000. Here is where the error is saying my issue is:

import React, { useState, useEffect } from 'react';
import { Card } from '../Components/Card/card';

export const TodoPage = () =>{

  const [todo, setTodo] = useState([])

  useEffect(()=> {
    fetch('/api').then(response => {
      if (response.ok) {
        return response.json() // Error occurs due to .json()
      } else {
        console.log(response)
      }
    }).then(data => console.log(data))
  },[]) 

  return(
    <>
      <Card/>
    </>
  )
}
Cade Harger
  • 1
  • 1
  • 4
  • 1
    What do the browser developer tools tell you? What are you logging on the back end? I agree - you're getting HTML (perhaps a 404?) when you're expecting JSON. – stdunbar May 22 '23 at 17:01

1 Answers1

0

After some tweaking, How to enable CORS in flask resolved my issue. Worth noting that this seems like it could cause security issues down the road. I also had to add the full URL to my fetch call: fetch('http://localhost:5000/api')

Cade Harger
  • 1
  • 1
  • 4