【问题标题】:Unable to redirect to url using Server Side Swift Perfect无法使用服务器端 Swift Perfect 重定向到 url
【发布时间】:2019-02-07 03:19:33
【问题描述】:

我正在为 Web 服务使用服务器端 Swift 完美框架。 用于提供静态/动态内容的 Mustache 模块。

我想在身份验证成功后重定向到主页后实现登录功能。 “我到处搜索,但没有找到任何此类重定向到 url 的功能”

这是我用于实现登录的代码-

func signin(request:HTTPRequest, response: HTTPResponse) {
    do {
        var errorMessage:String;
        var values = MustacheEvaluationContext.MapType()
        let email:String = request.param(name: "email")!
        let password:String = request.param(name: "password")!
        print("Email -> \(email) & Password -> \(password)")
        //After Authentication
        //Yay I want to go back to home page.
        mustacheRequest(request: request, response: response, handler: MustacheHelper(values: values), templatePath: webroot + "/index.html")
        // Sadly this doesn't work, it just renders the homepage without changing the url or 'without redirecting'
        response.completed()
} catch {
        print(error)
        logError(error.localizedDescription)
        response.setBody(string: "An error occured \(error)").completed()
    }
}

我认为 PerfectlySoft 公司会考虑使用此功能。也许我应该报告它。 任何人都知道我的问题可能是什么解决方案?请告诉。 谢谢。

【问题讨论】:

    标签: swift url-redirection perfect server-side-swift


    【解决方案1】:

    最后我自己想出了解决方案。 PerfectHTTP 或 PerfectHTTPServer 模块本身不包含 url 重定向的此功能。您必须通过 PerfectlySoft 导入另一个模块 -> Perfect-OAuth2。 'redirect' 方法直接在 HTTPResponse 扩展下声明。或者你可以通过像这样添加自己的来做到这一点,

    extension HTTPResponse {
        public func redirect(path: String) {
            self.status = .found
            self.setHeader(.location, value: path)
            self.completed()
        }
    }
    

    我希望这会有所帮助!

    【讨论】:

    • 非常感谢!你拯救了我的一天?
    • 完美的框架让我开始使用服务器端 swift,但我不再使用这个框架,因为它的竞争对手 (Vapor) 不断提供更新并使用最新的低级 swift API。我不知道这个 Perfect 框架的未来。我建议你使用 Vapor 4 框架vapor.codes。现已正式发布。
    猜你喜欢
    • 2020-07-02
    • 2016-02-28
    • 2011-09-18
    • 2021-04-10
    • 2011-10-07
    • 1970-01-01
    • 2011-08-18
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多