Форма Javascript отправляется дважды - PullRequest
1 голос
/ 16 апреля 2019

У меня есть форма входа, которая работает с 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>

Ниже мой сервлет (куда отправляется формак) на случай, если вы заинтересованы

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.

1 Ответ

1 голос
/ 16 апреля 2019

Это утверждение является виновником:

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, но независимо от того, что происходит в остальной части вашей функции, он будет выполнен и отправит дополнительный запрос GET вашему сервлету.

И поскольку ваш сервлет не различает запросы GET и POST (все перенаправляется на processRequest()), вы видите вывод, который видите.

...