【发布时间】:2020-08-20 22:27:44
【问题描述】:
我正在通过 Javascript (FETCH) 调用我的 Flask 视图函数 (API)。
我在使用 GET 方法时取得了成功,但是在使用 PATCH 方法时,我收到了 400 错误代码 (加载资源失败:服务器响应状态为 400 (BAD REQUEST))。
我查看了 url,似乎没问题,并且 ID 作为整数传递,所以不知道它为什么会给出这个错误消息。
此函数 (load_follow_link) 正在通过 GET 获取并将我的“关注”更新为“取消关注”标签(此处没有错误):
function load_follow_link(id) {
apply_csrf_token();
fetch(`/follow_unfollow/${id}`)
.then(response => response.json())
.then(data => {
if (data.is_following)
document.getElementById('follow-unfollow-btn').innerHTML = 'Unfollow';
else
document.getElementById('follow-unfollow-btn').innerHTML = 'Follow';
document.getElementById('followers-count').innerHTML = data.followers_count;
document.getElementById('following-count').innerHTML = data.following_count;
});
}
这是触发错误消息的 PATCH 函数 (follow_unfollow)。它应该调用视图函数并更新数据库:
function follow_unfollow(id) {
apply_csrf_token();
fetch(`/follow_unfollow/${id}`, {
method: 'PATCH'
})
.then(() => {
load_follow_link(id);
});
}
查看函数(请求方法为PATCH时不执行)
@app.route('/follow_unfollow/<int:tutor_id>', methods=['GET','PATCH'])
@login_required
def follow_unfollow(tutor_id):
""" GET: returns if user is following the tutor, followers and following total
PUT: follow or unfollow
"""
user = Users.query.get(current_user.id)
try:
tutor = Tutors.query.get(tutor_id)
except NoResultFound:
return JsonResponse({"error": "Tutor not registered"}, status=401)
following_count = user.following_total()
followers_count = tutor.followers_total()
is_following = user.is_following(tutor)
if request.method == 'GET':
return jsonify(is_following=is_following, followers_count=followers_count,
following_count=following_count)
elif request.method == 'PATCH':
if is_following:
user.unfollow(tutor)
else:
user.follow(tutor)
db.session.commit()
return success.return_response(message='Successfully Completed', status=204)
else:
return jsonify(error="GET or PUT request required", status=400)
感谢您的帮助
【问题讨论】:
-
在函数内部测试
print(request.method),确保你有PATCH
标签: javascript rest flask