gpt4 book ai didi

Javascript 表单提交两次

转载 作者:行者123 更新时间:2023-11-30 19:38:16 25 4
gpt4 key购买 nike

我有一个使用 Firebase auth 并连接到 servlet 的登录表单。问题是它被提交了两次。请检查以下内容。

javascript代码

function toggleSignIn() 
{
if (firebase.auth().currentUser)
{
// [START signout]
//window.location.href = 'LoadSellPendingApprovals'
alert('existing user');
firebase.auth().signOut();
// [END signout]
} else {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}

if (password.length < 4) {
alert('Please enter a password.');
return;
}

// Sign in with email and pass.
// [START authwithemail]
firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser)
{
var email = firebase.auth().currentUser.email;
//alert(email);
// console.log(email) contains email
const options = {
method: 'POST',
//url: 'LoginValidator',
headers: {
// set appropriate headers, assuming json here
//"Content-Type": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
// form body, assuming json
//body: JSON.stringify(email)
body: `email=${email}`
}
alert(email);
url = 'LoginValidator'
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
. catch(e => console.error(e))
window.location.href = 'LoginValidator'
})

.catch(function(error)
{
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode === 'auth/wrong-password')
{
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
document.getElementById('quickstart-sign-in').disabled = false;
// [END_EXCLUDE]
});
//alert('hi');
// [END authwithemail]
}
document.getElementById('quickstart-sign-in').disabled = true;

}

我的 HTML 表单

<form id="login-form" class="form" action="" method="post">
<div class="form-group">
<input type="text" name="email" id="email" class="form-control login-input" placeholder="username">
</div>
<div class="form-group">
<input class="form-control login-input" type="password" placeholder="Password" id="password" name="password">
<i id="open" class="fa fa-eye fa-2x"></i>
<i id="closed" class="fa fa-eye-slash fa-2x"></i>
</div>
<div class="form-group">
<input type="submit" id="quickstart-sign-in" name="quickstart-sign-in" class="form-control btn btn-info btn-md login-bt" value="Login" onclick="toggleSignIn()">
</div>
<div class="form-group text-center forgot">
<a href="#">Forgot username</a> / <a href="#">password?</a>
</div>
</form>

如果您有兴趣,下面是我的 servlet(提交表单的地方)

public class LoginValidator extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

String email = request.getParameter("email");
System.out.println("Printing email: "+email);

try {

System.out.println("inside try");

User user = new User();
UserRight userRight = new UserRight();

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

//Get user
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<User> call = endPoint.getUserByEmail(email);
user = call.execute().body();

System.out.println(user.getName());

//Get user rights
Call<UserRight> userRightCall = endPoint.getUserRightByID(user.getUserRights().getIduserRight());
userRight = userRightCall.execute().body();

System.out.println(userRight.getUserRight());

if(userRight.getUserRight().equals("admin"))
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("LoadSellPendingApprovals");
requestDispatcher.forward(request, response);
}
else
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.html");
requestDispatcher.forward(request, response);
}


} catch (Exception e) {
e.printStackTrace();
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}

在我的IDE控制台输出如下(输出由servlet打印)

Printing email: email@example.com
inside try
Printing email: null
inside try
java.lang.IllegalArgumentException: Path parameter "email" value must not be null.

最佳答案

这个语句是罪魁祸首:

window.location.href = 'LoginValidator'

它出现在这个代码块中:

fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
window.location.href = 'LoginValidator' // <= HERE

缩进让它看起来像是 catch block 的一部分,但无论您的函数的其余部分发生什么,它都会被执行并向您的 servlet 发送一个额外的 GET 请求.

并且由于您的 servlet 不区分 GET 和 POST 请求(所有内容都重定向到 processRequest()),您看到的是您所看到的输出。

关于Javascript 表单提交两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com