我正在使用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
});
在errorFuction中,我会告诉用户其用户名或密码不正确,等等。
在后端,我的/ login路由如下所示
@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')
但是在客户端,浏览器不会重定向,如果我在完整功能中查看响应对象,我会看到通常从我的“ /”路由返回的内容:200 OK和index.html模板。
我的问题是:
有什么方法可以拦截客户端重定向?
我认为问题是因为jquery发起了请求而不是浏览器。
我解决此问题的第一个尝试是使用make_response并设置Location标头构造自己的响应,但这导致了相同的行为。我当前的解决方案是返回200,然后客户端执行window.location = "/"此操作,但这似乎很hack