简体   繁体   中英

Javascript form submits twice

I have a login form which works with Firebase auth and connects to a servlet . The issue is it get submitted twice. Please check the below.

javascript code

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;

            }

My HTML form

<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>

Below is my servlet (where the form is submitted to) in case you are interested

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>

}

In my IDE console the output is as follows (the output is printed by the servlet )

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

This statement is the culprit:

window.location.href = 'LoginValidator'

It appears in this code block:

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

The indenting makes it look like it would be part of the catch block, but regardless of what happens in the rest of your function, this will get executed and send an additional GET request to your servlet.

And since your servlet doesn't distinguish between GET and POST requests (everything is redirected to processRequest() ), you're seeing the output you're seeing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM