简体   繁体   English

未从 Flask 后端接收 React-Native 前端

[英]Not receiving on React-Native frontend from Flask backend

I'm new to React Native and trying to build an app.我是 React Native 的新手,正在尝试构建一个应用程序。 I'm confused on how exactly to "connect" the backend and frontend.我对如何准确地“连接”后端和前端感到困惑。 I have added a proxy in package.json as most tutorials state:作为大多数教程 state,我在package.json中添加了一个代理:

{
  "name": "frontend",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "proxy": "http://127.0.0.1:5000",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~44.0.0",
    "expo-status-bar": "~1.2.0",
    "react": "17.0.1",
    "react-dom": "^17.0.1",
    "react-native": "0.64.3",
    "react-native-web": "^0.17.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

I also have these two functions:我也有这两个功能:

import React, {useEffect, useState} from 'react';
import test from './components/Home';

function App() {
  test();
  return (
    <div> </div>
  )
}

export default App;
import React, {useEffect, useState} from 'react';

function test() {
    useEffect(() => {
        fetch("/")
        .then(response => response.json()
        .then(data => {
            console.log(data)
        })
    )}, []);
}

export default test;

Right now, I'm just trying to print out the data in the console to see if the data is actually be received correctly (it's not) as I am getting an Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data error in the console.现在,我只是想在控制台中打印出数据,看看数据是否真的被正确接收(它不是),因为我得到一个Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

however, the data I am trying to get printed out comes from my backend which currently looks like this:但是,我试图打印出来的数据来自我的后端,目前看起来像这样:

from flask import Flask

app = Flask(__name__)

# API Routes
@app.route("/", methods=["GET"])
def home():
    return {"TEST": ["1", "2", "3"]}

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

Going back to my test function in the JS file, if I change response.json() to response.text() , the error goes away but the console logs this:回到 JS 文件中的测试 function ,如果我将response.json()更改为response.text() ,错误就会消失,但控制台会记录以下内容:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
    <!-- 
      This viewport works for phones with notches.
      It's optimized for gestures by disabling global zoom.
     -->
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1.00001, viewport-fit=cover"
    />
    <title>portfolio</title>
    <style>
      /**
       * Extend the react-native-web reset:
       * https://github.com/necolas/react-native-web/blob/master/packages/react-native-web/src/exports/StyleSheet/initialRules.js
       */
      html,
      body,
      #root {
        width: 100%;
        /* To smooth any scrolling behavior */
  ... and much more HTML

So it seems like I'm not receiving data from my backend.所以看起来我没有从我的后端接收数据。 Is there something obvious I am missing?我有什么明显的遗漏吗? Thanks谢谢

You must configure Cross-origin to allow flask to receive the request from react.您必须配置Cross-origin以允许 flask 接收来自 react 的请求。

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})

# API Routes
@app.route("/", methods=["GET"])
def home():
    return {"TEST": ["1", "2", "3"]}

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

For more details on the subject: flask-cors有关该主题的更多详细信息: flask-cors

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

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