如何解决gin-gonic 重定向 HTML 跟随 POST,来自 Javascript XMLHttpRequest
我正在尝试使用 Gin-gonic 构建登录页面,但在重定向浏览器时遇到问题。
main.go
router.GET("/login",getLoginPage)
router.POST("/login",authentication.Login)
router.GET("/dashboard",showMainPage)
如果用户按下 html 中的按钮
login.html
<input a href="javascript:void(0);" class="btn btn-primary btn-user btn-block" id="loginButton" value="Login"></input>
然后,Javascript 功能将起作用。我这样编码的原因是,我了解到在发送到服务器之前应该对 UserID 和 Password 进行哈希处理。 (据我所知,由于某种安全问题,例如窃听)
login.js
document.getElementById("loginButton").addEventListener("click",tryLogin,false);
// Get user inputs like ID and PW
var request = new XMLHttpRequest();
request.open("POST","/login");
request.send(formData);
现在,router.POST("/login",authentication.Login)
将起作用。
auth.go
func Login(c *gin.Context) {
id := c.PostForm("id")
pw := c.PostForm("pw")
// Hash password again,Check Validation and Find user in database
// If all inputs are correct,Logged in.
c.Header("Content-Type","text/html")
c.HTML(http.StatusOK,"dashboard.html",gin.H{
"title": "title of my page","username": "I want to send some data like this","usernickname": "TyeolRik",}) // But the thing is c.HTML not directing as I want. but it returns well checked in Postman.
}
但是 c.HTML 不会在浏览器中显示呈现的 HTML 屏幕(Chrome 和 Edge 已检查),而且 c.Redirect()
也不起作用。
auth.go
func Login(c *gin.Context) {
id := c.PostForm("id")
pw := c.PostForm("pw")
// Hash password again,Check Validation and Find user in database
c.Redirect(http.StatusMovedPermanently,"/dashboard")
}
如何轻松重定向 HTML?我暂时在 Javascript 中使用了 window.location.href = '/dashboard';
。但它不能像使用 gin.H{something}
对我有什么建议吗?
解决方法
感谢@mkopriva,我发现javascript 中的XMLHttpRequest()
不适用于gin.gonic 的*gin.Context.HTML()
当服务器返回时,浏览器不会使用 XMLHttpRequest()
重定向。
最终代码(运行良好)
login.js
function tryLogin() {
const email = document.getElementById("loginFormEmail").value;
const pw = document.getElementById("loginFormPassword").value;
var hashedPW = sha3_512(pw);
var hashedForm = document.createElement("form");
hashedForm.setAttribute("charset","UTF-8");
hashedForm.setAttribute("Content-Type","multipart/form-data");
hashedForm.setAttribute("method","POST"); // Post
hashedForm.setAttribute("action","/login"); // URL destination
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type","hidden");
hiddenField.setAttribute("name","email");
hiddenField.setAttribute("value",email);
hashedForm.appendChild(hiddenField);
hiddenField = document.createElement("input");
hiddenField.setAttribute("type","password");
hiddenField.setAttribute("value",hashedPW);
hashedForm.appendChild(hiddenField);
document.body.appendChild(hashedForm);
hashedForm.submit();
}
当服务器验证 POST-ed 登录时,然后
auth.go
// Some validation
// If ID and PW is right,c.Redirect(http.StatusMovedPermanently,"/dashboard")
这有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。