[英]Not receiving on React-Native frontend from Flask backend
我是 React Native 的新手,正在尝试构建一个应用程序。 我对如何准确地“连接”后端和前端感到困惑。 作为大多数教程 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
}
我也有这两个功能:
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;
现在,我只是想在控制台中打印出数据,看看数据是否真的被正确接收(它不是),因为我得到一个Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
。
但是,我试图打印出来的数据来自我的后端,目前看起来像这样:
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)
回到 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
所以看起来我没有从我的后端接收数据。 我有什么明显的遗漏吗? 谢谢
您必须配置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)
有关该主题的更多详细信息: flask-cors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.