简体   繁体   English

使用 SyntaxError 调试 React/Flask 连接:Unexpected token < in JSON at position 0

[英]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.我正在关注https://blog.miguelgrinberg.com/post/how-to-create-a-react--flask-project在使用 npx npx create-react-app并添加一个单个烧瓶文件。

package.json

I've set up a proxy at "proxy": "http://localhost:5000" with a new script command of yarn start-backend .我已经在"proxy": "http://localhost:5000"设置了一个代理,并使用了一个新的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.我已经使用 MaterialUI 设置了一个Button ,它调用一个函数来记录 JSON 响应。

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.在顶级目录中,我创建了一个名为app的目录,其中包含一个app.py以下代码的app.py文件。

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当我使用yarn startyarn start-backend并单击按钮时,出现以下错误

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/ .我尝试使用http://localhost:5000/将烧瓶文件移动到顶级目录到公共目录。 Any help is appreciated, thank you!任何帮助表示赞赏,谢谢!

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);
        })

Ok, so being new to JavaScript/ReactJS it seems like I was missing two things好吧,作为 JavaScript/ReactJS 的新手,我似乎错过了两件事

  1. I didn't have a return for the Promise which seems odd in that I thought you didn't have to return things我没有得到Promise的回报,这似乎很奇怪,因为我认为你不必回报东西

and

  1. Changing the path from / to /api/test seems to work.将路径从/更改为/api/test似乎有效。

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."}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM