bio*_*595 9 ajax jquery redirect http flask
我正在使用Flask作为我的后端和jQuery用于我正在进行的个人项目.
要登录我想这样做:
$.ajax({
type: "POST",
data: JSON.stringify(body), //username and password
contentType: 'application/json; charset=utf-8',
url: "/login",
success: successFunction,
error: errorFunction,
complete: completeFunction
});
Run Code Online (Sandbox Code Playgroud)
在errorFuction中,我会告诉用户他们的用户名或密码不正确等.
在后端我的/登录路线看起来像这样
@app.route("/login", methods=['GET', 'POST'])
def login():
if(request.method == "POST"):
#retrieve the username and password sent
data = request.json
if(data is None or not 'username' in data or not 'password' in data):
abort(400)
else:
count = User.query.filter(User.username == data['username']).count()
if(count == 0):
abort(404) #that user doesnt exist
else:
passIsCorrect = User.query.filter(User.username == data['username'],
User.password == data['password']).count()
if(passIsCorrect):
session['user'] = data['username']
return redirect(url_for('index'))
else:
abort(401)
else:
return render_template('login.html')
Run Code Online (Sandbox Code Playgroud)
但是在客户端,浏览器不会重定向,如果我查看完整函数中的响应对象,我会看到通常从我的'/'路由返回的内容:200 OK和index.html模板.
我的问题是:
有什么方法可以拦截使客户端重定向?
我认为问题是因为jquery正在启动请求而不是浏览器.
我解决此问题的第一个尝试是使用自己构建响应make_response并设置Location头,但这导致了相同的行为.我目前的解决方案是返回200,然后客户端window.location = "/",但这似乎是hacky
没有理由使用重定向与ajax,因为它将返回重定向的内容(在您的情况下只是内容与index端点).所以你可以返回重定向的链接,如果一切正常(状态200)而不是真正的重定向:
return url_for('index')
Run Code Online (Sandbox Code Playgroud)
并用你的js处理它:
var successFunction = function (data) {
// do something
window.location = data;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9014 次 |
| 最近记录: |