Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

332
Visualizações
Debugging React/Flask connection with SyntaxError: Unexpected token < in JSON at position 0

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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."}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda