如何使用标题重定向



如何在我的loginPost方法与header授权(我的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"]
}
})
}
})
}

Thymeleaf ViewController:

@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";
}
}

get请求后,我只有响应与html页面,但我需要重定向获取路由与渲染此页面。如果我做window.location="/api/user"我有回复401.

在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");

祝你今天愉快!

最新更新