我们正在尝试将 JSON 格式的 HTML 表单发送到 GO 代码。我们已经实现了这一点,但是,现在我们很困惑,因为我们无法使浏览器重定向到相应的网页。重定向指令直接在 Insomnia 上发送 json 可以正常工作(它返回成功状态并显示新页面),但在浏览器中则不行。也许我们遗漏了一些代码,但我们无法找到我们遗漏了什么。请帮忙。
发送json的javascript代码:
jQuery(document).on('submit', '#login', function(event){
event.preventDefault();
jQuery.ajax({
url: '/login/',
type: 'POST',
dataType: 'json',
data: JSON.stringify($(this).serializeFormJSON())
})
.done(function(response){
location.href = 'response';
})
.fail(function(resp){
console.log("resp");
})
.always(function(){
console.log("complete");
})
});
验证此表单的 Go 代码:
func POSTLoginHandler(w http.ResponseWriter, r *http.Request) {
var user users.User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
} else {
validCredentials, err := users.ValidarCredenciales(user)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else if validCredentials {
err = cookies.GenerarCookie(w, r, user.Email)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
http.Redirect(w, r, "/dashboard/", http.StatusSeeOther)
}
} else {
http.Redirect(w, r, "/forbidden/", http.StatusSeeOther)
}
}
}
func GetDashboardUser(w http.ResponseWriter, r *http.Request) {
exists, err := cookies.VerifyCookie(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else if exists {
http.ServeFile(w, r, "static/template.html")
} else {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}
慕哥6287543
相关分类