首页 > 解决方案 > scala akka 不重定向

问题描述

我有以下后端。如果转到“localhost:8080”,则通过从“/”重定向到“login”来加载登录页面。登录页面已加载。在提交登录表单时,会调用“perform-login”。但是,由于某种原因,没有重定向到“存储”页面。为什么?

PS如果手动请求页面“存储”,它会被加载。问题在于从“登录”页面重定向到“存储”页面。可能它与设置 cookie 有关,因为此命令也具有返回类型 Route。

Scala 版本:2.13.6,Akka HTTP 版本:10.2.6

object Backend {
    def main(args: Array[String]) = {
        implicit val system = ActorSystem(Behaviors.empty, "lowlevel")
        // needed for the future map/flatmap in the end
        implicit val executionContext: ExecutionContext = system.executionContext
        val topLevelRoute: Route = 
            concat(
                pathSingleSlash {
                    redirect("login", StatusCodes.PermanentRedirect)
                },
                path("login") {
                    complete("my login page")
                },
                path("storage") {
                    cookie("token") { tokenCookie =>
                        println("you managed to login, token:" + tokenCookie.value + "ENDLINE")
                        complete("my storage page")
                    }
                },
                path("perform-login") {
                    formFields("Username", "Password") { (username, password) =>
                        var isAbleToLogin = database.isUserLoggedIn(username, password)
                        if (isAbleToLogin == true) {
                            setCookie(HttpCookie("token", value="ThisIsMyStrongAccessToken")) {
                                //TODO: debug why does not redirect to main page
                                redirect("storage", StatusCodes.PermanentRedirect)
                            }
                        }
                        else {
                            reject(ValidationRejection("bad credentials"))
                        }
                    }
                },
                path(Remaining) { pathRest =>
                    reject(ValidationRejection("topLevelRoute, unknown path:" + pathRest + "ENDLINE"))
                }
        )

    val binding = Http().newServerAt("localhost", 8080).bind(topLevelRoute)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    binding
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done        
}

标签: scalaakkaakka-http

解决方案


解决方案:当我导航到“/”页面时,由于“文档/重定向”请求类型(如果分析网络),重定向到“/login”页面发生。但是,如果从“/login”页面重定向到“/storage”页面,请求类型为“xhr /redirect”,无法在服务器端完成,即我必须添加$(location).attr('href', 'storage')到我的 jQuery 脚本中才能完成工作。


推荐阅读