这是我第一次使用react和flask。我正在尝试使用react从烧瓶终点显示时间。我在Flask服务器上的状态为200,但是在浏览器上的请求不正确。它不包含响应代码,但是为红色,没有响应信息。
烧瓶在端口5000上,反应在3000上。我以“ proxy”:“ http:localhost:5000 /”的形式向我的package.json文件添加了代理。
网站说当前时间是0,这是错误的,我不认为React正在以某种方式接收烧瓶数据。烧瓶端正在打印时间,我在服务器端看到了200个代码。
烧瓶应用程序(app.py)与react应用程序(canoe-finder)一起包含在主目录中。
我很新来做出反应。因此,欢迎任何帮助。
反应码
import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [currentTime, setCurrentTime] = useState(0);
useEffect(() => {
fetch('http://localhost:5000/time').then(res => res.json()).then(data => {
setCurrentTime(data.time);
});
}, []);
return (
<div className="App">
<header className="App-header">
... no changes in this part ...
<p>The current time is {currentTime}.</p>
</header>
</div>
);
}
export default App;
当我使用fetch('/ time')而不是fetch('http:// localhost:5000 / time')时,出现此错误
Proxy error: Could not proxy request /time from localhost:3000 to http://localhost:5000:.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
烧瓶代码
from flask import Flask, render_template, redirect, url_for, request, jsonify, flash
import sqlite3
import time
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.automap import automap_base
app = Flask(__name__)
@app.route('/time')
def get_current_time():
print(time.time())
return jsonify('time', time.time())
答案 0 :(得分:0)
首先,在本地主机上运行的Flask服务器的正确语法为http://localhost:5000
。其次,当您fetch('/time')
处于开发中时,开发服务器将认识到它不是静态资产,并将您的请求代理到http://localhost:5000/time
作为后备。
如果您有兴趣,可以阅读有关此here的更多信息。
另外,当在useEffect中获取数据时,您应该具有某种加载状态变量。
import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [currentTime, setCurrentTime] = useState(0);
const [loading, setLoading] = useState(true)
useEffect(() => {
setLoading(true)
fetch('http://localhost:5000/time').then(res => res.json()).then(data => {
setCurrentTime(data.time);
});
setLoading(false)
}, []);
if (loading) return <h1>Loading data...</h1>
return (
<div className="App">
<header className="App-header">
<p>The current time is {currentTime}.</p>
</header>
</div>
);
}
export default App;