我如何在我的 loginPost 方法后使用標題授權重定向(我的 jquery 代碼):
$(document).ready(function (){
$("#form-login").submit(function (event){
event.preventDefault();
let $form = $(this),
email = $form.find("input[name='email'").val(),
password = $form.find("input[name='password'").val();
loginPost(email, password);
})
function loginPost(email, password) {
$.ajax({
url:"/api/auth/login",
type:"POST",
async:false,
data: {email, password},
success: function (data) {
let urlLogin;
if(data["role"] === "ROLE_USER") {
urlLogin = "/api/user"
} else {
urlLogin = "/api/admin"
}
$.ajax({
url:urlLogin,
type:"GET",
async: false,
headers: {
"Authorization": "Bearer " data["token"]
}
})
}
})
}
百里香視圖控制器:
@Controller
@RequestMapping("/api")
public class ViewController {
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping("/user")
public String userPage() {
return "user_page";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin")
public String adminPage() {
return "admin_page";
}
}
獲取請求后,我只有 hmtl 頁面的回應,但我需要通過呈現此頁面來重定向獲取路由。如果我做 window.location="/api/user" 我有回應 401。
uj5u.com熱心網友回復:
在 javascript 中,您可以通過
window.location.href = "http://www.example.com";. 在你的情況下,我建議你做類似window.location.href = "http://www.yoururl.com" urlLogin;或類似的事情。如果您只想使用 php(在服務器端)進行重定向,您可以通過設定Location標頭來執行此操作。您可以通過執行以下操作設定 Location 標頭:
$path = "/admin";
header("Location: " . $path);
或者header("Location: /admin");
祝你今天過得愉快!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482962.html
標籤:javascript jQuery 弹簧靴 弹簧安全 百里香叶
下一篇:回圈嵌套陣列時發生沖突的基準測驗
