来自 Flask 后端的 React 前端响应错误
React frontend response error from flask backend
我正在创建一个 React 应用程序,它利用作为 REST 的烧瓶后端 API。不幸的是,我一直在使用 fetch 命令时遇到问题,因为它似乎总是说 fetch failed loading: [method]。后端似乎可以很好地处理请求。
127.0.0.1 - - [20/Jul/2021 21:10:35] "GET /api/login HTTP/1.1" 200 -
我已经在 postman 中尝试了这个请求,它工作正常。我在 package.json
中使用 HTTP://localhost:5000
的代理,所以我认为这不是 CORS 问题,而且我也尝试过使用 flask_cors 无济于事。有没有人在使用 fetch API 之前经历过这样的事情?我是 javascript 的新手,所以可能有些地方我没有注意到。
谢谢。
Users.py(蓝图)
from . import bp
from flask import jsonify, request, make_response
@bp.route('/login', methods=['GET'])
def login():
return jsonify({'status': 'success'})
init.py(蓝图)
from flask import Blueprint
bp = Blueprint('rest', __name__)
from . import users
init.py(应用程序)
def create_app():
from .config import Config
app = Flask(__name__)
app.config.from_object(Config)
mail = Mail(app)
from .models import db, Visitor, User
db.init_app(app)
migrate = Migrate(app, db)
@app.shell_context_processor
def make_shell_context():
return {"config": Config, "db": db, "Visitor": Visitor, "User": User}
#jwt.init_app(app)
app.register_blueprint(api_bp, url_prefix='/api')
return app
请求(来自反应按钮事件处理程序)
export default function LoginUser(props) {
const [user, setUser] = useState({})
function handleChange(e) {
const { name, value } = e.target
switch (name) {
case 'email':
setUser({ ...user, email: value });
break;
case 'password':
setUser({ ...user, password: value });
break;
default:
break;
}
}
function handleSubmit(e) {
fetch('/api/login').then(res => res.json()).then().catch(error => console.log('error'))
}
return (
<Form>
<Form.Group className="mb-3" controlId="LoginEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email"
placeholder="Enter email"
name="email"
onBlur={handleChange} />
</Form.Group>
<Form.Group className="mb-3" controlId="LoginPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password"
placeholder="Password"
name="password"
onBlur={handleChange} />
</Form.Group>
<Button variant="primary" type="submit" onClick={handleSubmit}>
Submit
</Button>
</Form>
)
}
浏览器错误(勇敢)
handleSubmit @ main.chunk.js:781
callCallback @ vendors~main.chunk.js:24274
invokeGuardedCallbackDev @ vendors~main.chunk.js:24323
invokeGuardedCallback @ vendors~main.chunk.js:24383
invokeGuardedCallbackAndCatchFirstError @ vendors~main.chunk.js:24398
executeDispatch @ vendors~main.chunk.js:28633
processDispatchQueueItemsInOrder @ vendors~main.chunk.js:28665
processDispatchQueue @ vendors~main.chunk.js:28678
dispatchEventsForPlugins @ vendors~main.chunk.js:28689
(anonymous) @ vendors~main.chunk.js:28900
batchedEventUpdates @ vendors~main.chunk.js:42585
batchedEventUpdates @ vendors~main.chunk.js:24072
dispatchEventForPluginEventSystem @ vendors~main.chunk.js:28899
attemptToDispatchEvent @ vendors~main.chunk.js:26382
dispatchEvent @ vendors~main.chunk.js:26300
unstable_runWithPriority @ vendors~main.chunk.js:56804
runWithPriority @ vendors~main.chunk.js:31680
discreteUpdates @ vendors~main.chunk.js:42602
discreteUpdates @ vendors~main.chunk.js:24084
dispatchDiscreteEvent @ vendors~main.chunk.js:26266
努力改变
fetch('/api/login').then(res => console.log(res)).catch(error => console.log('error'))
到 fetch('/api/login').then(res => res.json()).then(result => console.log(result)).catch(error => console.log('error'))
.
因为使用 fetch,您的 'res' 只是一个 HTTP 响应,而不是实际的 JSON。所以你需要 res.json() 来获取 JSON 正文。
编辑版本
将 <Button variant="primary" type="submit" onClick={handleSubmit}>
更改为 <Button variant="primary" type="submit" onClick={(e)=>handleSubmit(e)}>
。还要在handleSubmit函数中加入e.preventDefault()
,防止页面刷新
注意:您应该在 api 登录
中传递您的用户
我正在创建一个 React 应用程序,它利用作为 REST 的烧瓶后端 API。不幸的是,我一直在使用 fetch 命令时遇到问题,因为它似乎总是说 fetch failed loading: [method]。后端似乎可以很好地处理请求。
127.0.0.1 - - [20/Jul/2021 21:10:35] "GET /api/login HTTP/1.1" 200 -
我已经在 postman 中尝试了这个请求,它工作正常。我在 package.json
中使用 HTTP://localhost:5000
的代理,所以我认为这不是 CORS 问题,而且我也尝试过使用 flask_cors 无济于事。有没有人在使用 fetch API 之前经历过这样的事情?我是 javascript 的新手,所以可能有些地方我没有注意到。
谢谢。
Users.py(蓝图)
from . import bp
from flask import jsonify, request, make_response
@bp.route('/login', methods=['GET'])
def login():
return jsonify({'status': 'success'})
init.py(蓝图)
from flask import Blueprint
bp = Blueprint('rest', __name__)
from . import users
init.py(应用程序)
def create_app():
from .config import Config
app = Flask(__name__)
app.config.from_object(Config)
mail = Mail(app)
from .models import db, Visitor, User
db.init_app(app)
migrate = Migrate(app, db)
@app.shell_context_processor
def make_shell_context():
return {"config": Config, "db": db, "Visitor": Visitor, "User": User}
#jwt.init_app(app)
app.register_blueprint(api_bp, url_prefix='/api')
return app
请求(来自反应按钮事件处理程序)
export default function LoginUser(props) {
const [user, setUser] = useState({})
function handleChange(e) {
const { name, value } = e.target
switch (name) {
case 'email':
setUser({ ...user, email: value });
break;
case 'password':
setUser({ ...user, password: value });
break;
default:
break;
}
}
function handleSubmit(e) {
fetch('/api/login').then(res => res.json()).then().catch(error => console.log('error'))
}
return (
<Form>
<Form.Group className="mb-3" controlId="LoginEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email"
placeholder="Enter email"
name="email"
onBlur={handleChange} />
</Form.Group>
<Form.Group className="mb-3" controlId="LoginPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password"
placeholder="Password"
name="password"
onBlur={handleChange} />
</Form.Group>
<Button variant="primary" type="submit" onClick={handleSubmit}>
Submit
</Button>
</Form>
)
}
浏览器错误(勇敢)
handleSubmit @ main.chunk.js:781
callCallback @ vendors~main.chunk.js:24274
invokeGuardedCallbackDev @ vendors~main.chunk.js:24323
invokeGuardedCallback @ vendors~main.chunk.js:24383
invokeGuardedCallbackAndCatchFirstError @ vendors~main.chunk.js:24398
executeDispatch @ vendors~main.chunk.js:28633
processDispatchQueueItemsInOrder @ vendors~main.chunk.js:28665
processDispatchQueue @ vendors~main.chunk.js:28678
dispatchEventsForPlugins @ vendors~main.chunk.js:28689
(anonymous) @ vendors~main.chunk.js:28900
batchedEventUpdates @ vendors~main.chunk.js:42585
batchedEventUpdates @ vendors~main.chunk.js:24072
dispatchEventForPluginEventSystem @ vendors~main.chunk.js:28899
attemptToDispatchEvent @ vendors~main.chunk.js:26382
dispatchEvent @ vendors~main.chunk.js:26300
unstable_runWithPriority @ vendors~main.chunk.js:56804
runWithPriority @ vendors~main.chunk.js:31680
discreteUpdates @ vendors~main.chunk.js:42602
discreteUpdates @ vendors~main.chunk.js:24084
dispatchDiscreteEvent @ vendors~main.chunk.js:26266
努力改变
fetch('/api/login').then(res => console.log(res)).catch(error => console.log('error'))
到 fetch('/api/login').then(res => res.json()).then(result => console.log(result)).catch(error => console.log('error'))
.
因为使用 fetch,您的 'res' 只是一个 HTTP 响应,而不是实际的 JSON。所以你需要 res.json() 来获取 JSON 正文。
编辑版本
将 <Button variant="primary" type="submit" onClick={handleSubmit}>
更改为 <Button variant="primary" type="submit" onClick={(e)=>handleSubmit(e)}>
。还要在handleSubmit函数中加入e.preventDefault()
,防止页面刷新
注意:您应该在 api 登录
中传递您的用户