Home > Back-end >  Debugging React/Flask connection with SyntaxError: Unexpected token < in JSON at position 0
Debugging React/Flask connection with SyntaxError: Unexpected token < in JSON at position 0

Time:10-13

I'm following https://blog.miguelgrinberg.com/post/how-to-create-a-react--flask-project attempting to connect a simple Flask backend with ReactJS after using npx create-react-app and adding a single flask file.

package.json

I've set up a proxy at "proxy": "http://localhost:5000" with a new script command of yarn start-backend.

  "scripts": {
    "start": "react-scripts start",
    "start-backend": "cd app && python3 app.py",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

nav.js

I've set up a Button using MaterialUI that calls a function to log a JSON response.

class Nav extends React.Component {

    clicked() {
        fetch('/').then(res => {
            console.log(res.json());
        }).then(data => {
            console.log(data);
        })
    }

    render() {
        return (
            <Box sx={{ flexGrow: 1}}>
                <AppBar position="static">
                    <Toolbar>
                        <SignUpForm onClick={() => this.clicked()} />
                    </Toolbar>
                </AppBar>
            </Box>
        )
    }
}

In the top level directory I've created a directory called app that has an app.py file with the following code.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return {"msg": "homepage from the backend."}

if __name__ == "__main__":
    app.run(port=5000, debug=True)

When I use yarn start and yarn start-backend and click the button, I get the error below

Promise {<pending>}
nav.js:14 undefined
VM1769:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Attempting to debug, but I'm unfortunately not getting anywhere. There's related questions but nothing seems to work. I've tried moving the flask file to the top level directory, to public, using http://localhost:5000/. Any help is appreciated, thank you!

CodePudding user response:

I hope this work for you.

fetch('/', {
     headers : { 
          'Content-Type': 'application/json',
          'Accept': 'application/json'
         }
}).then(res => {
            console.log(res.json());
        }).then(data => {
            console.log(data);
        })

CodePudding user response:

Ok, so being new to JavaScript/ReactJS it seems like I was missing two things

  1. I didn't have a return for the Promise which seems odd in that I thought you didn't have to return things

and

  1. Changing the path from / to /api/test seems to work.

I'll have to dig further to understand but for now it resolves my issue.

Here's the code that's changed

    clicked() {
        fetch('/api/test')
            .then(res => {return res.json()} )
            .then(
                data => {
                    console.log(data)
            })
    }

and


@app.route("/api/test")
def home():
    return {"msg": "homepage from the backend."}
  • Related