python - 来自烧瓶后端的反应前端响应错误
问题描述
我正在创建一个反应应用程序,它利用用作 REST API 的烧瓶后端。不幸的是,我一直遇到 fetch 命令的问题,因为它似乎总是说 fetch failed loading: [method]。后端似乎可以很好地处理请求。
127.0.0.1 - - [20/Jul/2021 21:10:35] “GET /api/login HTTP/1.1”200 -
我已经在邮递员中尝试过这个请求,它工作正常。我在我的中使用代理,HTTP://localhost:5000
所以package.json
我认为这不是 CORS 问题,我也尝试使用 flask_cors 无济于事。有没有人在使用 fetch API 之前经历过这样的事情?我对javascript相当陌生,所以可能有些东西我没有注意到。
谢谢。
用户.py(蓝图)
from . import bp
from flask import jsonify, request, make_response
@bp.route('/login', methods=['GET'])
def login():
return jsonify({'status': 'success'})
初始化.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$1 @ 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$1 @ vendors~main.chunk.js:31680
discreteUpdates$1 @ 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)}>
。还要添加e.preventDefault()
handleSubmit函数来防止页面刷新。
注意:您应该在 api login 中传递您的用户
推荐阅读
- angular - 使用 Angular Universal 和 Webpack Server 时未定义 @ng-idle/core 文档
- sql - 如何使用gorm更新sql中的嵌套表?
- kubernetes - 如何在 Google Cloud Platform 上部署 GRPC 服务器和客户端?
- typo3 - 是否可以禁用 TYPO3 TCA 记录的翻译
- php - 如何禁用 symfony 表单中的必填字段?
- css - 如何正确生成 Sass 主题
- java - inputStream = new FileInputStream(path) 不工作
- mysql - 可以使用分析/窗口函数来查找以其他单词开头的单词子集吗?
- dart - Flutter - 基于第一个下拉列表中选择的选项的下拉选项
- javascript - 更改自定义主题 Material-UI