【问题标题】:Ajax redirect with http.StatusOK handled by ajax error and not being redirectedAjax 重定向与 http.StatusOK 由 ajax 错误处理且未被重定向
【发布时间】:2019-11-30 00:52:41
【问题描述】:

我在 Go 中有 func(我已删除所有错误处理以使其简短)

func PostLoginAjax(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        userEmail := r.FormValue("Email")
        userPassword := r.FormValue("Password")
        db := r.Context().Value( "db").(*sqlx.DB)
        sessionStore := r.Context().Value( "sessionStore").(sessions.Store)
        u := models.NewUser(db)
        user, err := u.GetUserByEmailAndPassword(nil, userEmail, userPassword)
        session, _ := sessionStore.Get(r, "superadmin-session")
        session.Values["user"] = user
        err = session.Save(r, w)
        log.Info("All Success, redirecting to: ", "/")
        w.Header().Set("Location", "/")
        w.WriteHeader(http.StatusFound)
    }
}

下面是正在使用的模板中的 sn-p

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
        $(document).ready(function(){
            $("#login-submit").on('click', function(){
                $.ajaxSetup({async: true, cache: false});
                $.ajax({
                    url: '/login', // url where to submit the request
                    type : "POST", // type of action POST || GET
                    data : $("#form-login").serialize(), // post data || get data
                    success: function (response, status, xhr) {
                        console.log("success");
                        console.log(status);
                        console.log(xhr);
                        console.log(response);
                        },
                    error: function (errMsg) {
                        console.log("error");
                        console.log(errMsg);
                        $("#formErrorMessage").html(errMsg);
                    },
                    complete: function(resp) {
                        console.log("complete");
                        console.log(resp);
                    }
                })
            });
        });
</script>

如果我只是上面显示的代码,当我点击“登录”按钮并检查控制台日志时,我会看到如下所示的内容

我不明白的是为什么页面没有被重定向,因为在 devtools 的“网络”选项卡中我看到状态为 302,而在控制台日志中我看到状态为 200。为什么会有这种差异。当我只是简单地刷新页面时,它可以正常工作并将我带到登录页面,然后我必须从那里注销才能再次测试。

我怎样才能真正做到这一点,比如使用 ajax 提交表单,然后在验证电子邮件和密码时重定向。

如果我从 func 中删除以下行,则响应由 ajax 的错误部分处理,并且会发生同样的事情,我会在控制台日志中的响应文本中获得完整的 HTML,#formErrorMessage 实际上显示了 HTML(已解析) 与所有图像和文字。当我只是简单地刷新页面时,它会进入登录页面,然后我必须从那里注销。

w.Header().Set("Location", "/")

我想知道,这是正常行为还是我遗漏了什么。我最初使用没有 AJAX 的普通 http.Redirect 实现了这一点,它工作正常,现在我试图使用 AJAX 让它工作,但它只是不工作。

【问题讨论】:

标签: jquery ajax go


【解决方案1】:

当您在服务器上设置 Location 标头时,它仅针对这一 AJAX 请求设置。它被正确地重定向到/,这就是为什么您可以在浏览器控制台中看到该html。

由于此请求与您的“正常”网络浏览器流量分开,因此您必须自己处理 JavaScript 代码中的重定向,例如把这个放到成功函数中:

document.location = document.location.protocol + "//" + document.location.host

您还可以实现一个用于登录的 API 端点,该端点返回登录是否成功,然后在您的 AJAX 请求中调用此端点。成功后,您的客户端代码必须处理重定向。

【讨论】:

    猜你喜欢
    • 2011-05-09
    • 2010-12-20
    • 2012-06-25
    • 2023-03-14
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    相关资源
    最近更新 更多