我正在开发一个带有微服务的 Web 项目。在后端,我有一个登录服务,它负责检查用户凭据并返回一个有效的 JWT。我有另一个名为 Views 的服务,它负责为 UI 提供服务并将请求发送到其他服务。来自客户端的每个请求首先访问 Views 服务,然后将请求传递给适当的服务。
视图服务中向“/login”路由发送ajax请求的代码:
function login(){
$('#login-form').submit(function(){
$.ajax({
url: $('#login-form').attr('action'),
type: 'POST',
data : $('#login-form').serialize(),
success: function(res, status, xhr){
window.localStorage.setItem("x-access-token", xhr.getResponseHeader("x-access-token"));
$.ajax({
url: "/user/profile",
type: "GET",
headers: {
"x-access-token": window.localStorage.getItem("x-access-token")
},
success: function () {
window.location.replace("/user/profile")
},
error: function (response) {
alert("Error in GET: " + response)
}
});
}, error: function (response) {
alert(response)
}
})
});
}
将请求传递给登录服务的代码:
@views_blueprint.route("/login", methods=["POST"])
def user_login():
email = request.form["email"]
password = request.form["password"]
r = requests.post("http://login:5000/login", json={"data": {"email": email, "password": password}})
try:
login_resp = r.json()
if login_resp["status"] == 201:
@after_this_request
def send_token(response):
response.headers["x-access-token"] = login_resp["token"]
return response
return json.dumps(login_resp)
else:
return render_template("/error/error.html", error_code=login_resp["status"], error_message=login_resp["message"])
except Exception as e:
return render_template("/error/error.html", error_code=500, error_message=f"Error occurred. {e}")
我可以成功发送登录请求并取回令牌并将其存储在 localStorage 中。我遇到的问题是,登录后我需要将用户重定向到受保护的路由,并且需要将 JWT 添加到请求标头中。我试图通过function login(). 但是,永远不会发送 GET 请求,而是 Flask 呈现user_login()函数中返回的 JSON 对象。
我该如何克服这个问题?如果我正在做的事情是错误的,有人能指出我正确的方向吗?