简体   繁体   English

如何使用标题重定向

[英]How to redirect with headers

How i can redirect after my loginPost method with header Authorization(my jquery code):我如何使用 header 授权(我的 jquery 代码)在我的 loginPost 方法之后重定向:

$(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: Thymeleaf 视图控制器:

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

}

After get request i have only response with hmtl page, but i need to redirect get route with rendering this page.获取请求后,我只有 hmtl 页面的响应,但我需要通过呈现此页面来重定向获取路由。 If i doing window.location="/api/user" i have response 401.如果我执行 window.location="/api/user" 我有响应 401。

In javascript you can change the page via window.location.href = "http://www.example.com";在 javascript 中,您可以通过window.location.href = "http://www.example.com"; . . In your case I would suggest you to do something like window.location.href = "http://www.yoururl.com" + urlLogin;在你的情况下,我建议你做一些像window.location.href = "http://www.yoururl.com" + urlLogin; or something like this.或类似的东西。 If you want to redirect using just the php (on server side) you can do this by setting the Location header. You can set the Location header by doing this:如果您只想使用 php(在服务器端)进行重定向,您可以通过设置Location header 来执行此操作。您可以通过执行以下操作来设置位置 header:

$path = "/admin";
header("Location: " . $path);

or header("Location: /admin");header("Location: /admin");

Have a nice day!祝你今天过得愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM