简体   繁体   English

使用Node.js时Android-Volley发布错误

[英]Android-volley post error when working with Node.js

I know this question might have been asked multiple times but none of the solutions seems to work for me. 我知道这个问题可能已被问过多次,但没有一种解决方案适合我。 In my android volley post request i pass in username and password but each time i click login it always say 'invalid username and password' even though the credentials are correct and it work's well with postman. 在我的android volley帖子请求中,我传递用户名和密码,但是每次单击登录时,即使凭据正确且与邮递员都很好,它也总是说“用户名和密码无效”。 Here my code below: 这是我的代码如下:

Login Node.js 登录Node.js

router.post('/login', function(req,res,next){
  var user = {
    username: req.body.username,
    password: req.body.password
  };

  connection.query("SELECT id, fullname, username, email_address, createdAt FROM users WHERE username=?  OR email_address=? AND password=? LIMIT 1",[user.username, user.username, user.password], function(err, rows, field){
      if(err) throw err;
      if(rows.length > 0){
        res.json({
            success: '1',
            message: 'Login Successful',
            id: rows[0],
            fullname: rows[1],
            username: rows[2],
            email: rows[3],
            createdAt: rows[4]
        });
      }else{
        res.json({
            success: '0',
            message: 'Invalid username or password'
        });
      }
  });
});

Login on client side(android): 在客户端登录(Android):

private void login(final String uname, final String upass) {
    //192.168.1.101:5000/api/users/1
   final String url = "http://192.168.1.100:5000/api/users/login";
   RequestQueue queue = Volley.newRequestQueue(getActivity());

    JsonObjectRequest rq = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
              if(response.getString("success") != null) {
                final int success = Integer.parseInt(response.getString("success"));
                    if (success == 1) {
                        JSONObject uid = response.getJSONObject("id");
                        int id = uid.getInt("id");
                        String fullname = uid.getString("fullname");
                        String username = uid.getString("username");
                        String email = uid.getString("email");
                        String createdAt = uid.getString("createdAt");
                        SuperToast successToast = new SuperToast(getActivity(), Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN));
                        //successToast.setText(id + " " + fullname + " " + username + " " + email + " " + createdAt);
                        successToast.setText(response.getString("message"));
                        successToast.setDuration(SuperToast.Duration.LONG);
                        successToast.setGravity(Gravity.CENTER, 0, 0);
                        successToast.show();
                    } else if (success == 0) {
                        SuperToast errorToast = new SuperToast(getActivity(), Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN));
                        errorToast.setText(response.getString("message"));
                        errorToast.setDuration(SuperToast.Duration.MEDIUM);
                        errorToast.setGravity(Gravity.CENTER, 0, 0);
                        errorToast.show();
                    } else {
                        SuperToast errorToast = new SuperToast(getActivity(), Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN));
                        errorToast.setText("Invalid Request");
                        errorToast.setDuration(SuperToast.Duration.MEDIUM);
                        errorToast.setGravity(Gravity.CENTER, 0, 0);
                        errorToast.show();
                    }
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            SuperToast.create(getActivity(), error.getMessage(), SuperToast.Duration.LONG).show();
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("username", uname);
            params.put("password", upass);
            return params;
        }
    };
    //MySingleton.getInctance(getActivity().getApplicationContext()).addToRequestQueue(rq);
    queue.add(rq);
}

Any help will be much appreciated, thank you in advance. 任何帮助将不胜感激,在此先感谢您。

You're not sending the username and password on the request body: 您没有在请求正文上发送用户名和密码:

JsonObjectRequest rq = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

Create the body and set on the request: 创建主体并根据要求设置:

JSONObject body = new JSONObject();
body.put("username", uname);
body.put("password", upass);

JsonObjectRequest rq = new JsonObjectRequest(Request.Method.POST, url, body, new Response.Listener<JSONObject>() {

I've fixed it, turns out it was the email response that was null and throwing exceptions and thanks to Tiago Ribeiro the code is finally working, Here's the updated code 我已经修复了它,原来是电子邮件响应为null,并引发异常,感谢Tiago Ribeiro,代码终于可以正常工作了,这是更新的代码

Login.js: Login.js:

    router.post('/login', function(req,res,next){
    function encrypt(text){
        var cipher =  crypto.createHash('sha1')
            .update(text)
            .digest('hex');
        return cipher;
    }
    var uPassword = encrypt(req.body.password.toString());
  var user = {
    username: req.body.username,
    password: uPassword
  };

  connection.query("SELECT id, fullname, username, email_address, createdAt FROM users WHERE (username=? OR email_address=?) AND password=? LIMIT 1",[user.username, user.username, user.password], function(err, rows, field){
      if(err) throw err;
      if(rows.length > 0){
        res.json({
            success: 1,
            message: 'Login Successful',
            id: rows[0],
            fullname: rows[1],
            username: rows[2],
            email_address: rows[3],
            createdAt: rows[4]
        });
      }else{
        res.json({
            success: 0,
            message: 'Invalid username or password'
        });
      }
  });
});

Android Login: Android登录:

    private void login(final String uname, final String upass) {
        //192.168.1.101:5000/api/users/1
       final String url = "http://192.168.1.100:5000/api/users/login";
       RequestQueue queue = Volley.newRequestQueue(getActivity());
        JSONObject params = new JSONObject();
        try {
            params.put("username", uname);
            params.put("password", upass);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest rq = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    final int success = response.getInt("success");
                      Log.d("Response", String.valueOf(success));
                        if (success == 1) {
                            JSONObject uid = response.getJSONObject("id");
                            int id = uid.getInt("id");
                            String fullname = uid.getString("fullname");
                            String username = uid.getString("username");
                            String email = uid.getString("email_address");
                            String createdAt = uid.getString("createdAt");
                            SuperToast successToast = new SuperToast(getActivity(), Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN));
                            successToast.setText(id + " " + fullname + " " + username + " " + email + " " + createdAt);
                           // successToast.setText(response.getString("message"));
                            successToast.setDuration(SuperToast.Duration.LONG);
                            successToast.setGravity(Gravity.CENTER, 0, 0);
                            successToast.show();
                        } else if (success == 0) {
                            SuperToast errorToast = new SuperToast(getActivity(), Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN));
                            errorToast.setText(response.getString("message"));
                            errorToast.setDuration(SuperToast.Duration.MEDIUM);
                            errorToast.setGravity(Gravity.CENTER, 0, 0);
                            errorToast.show();
                            Log.d("Response", response.toString());
                        } else {
                            SuperToast errorToast = new SuperToast(getActivity(), Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN));
                            errorToast.setText("Invalid Request");
                            errorToast.setDuration(SuperToast.Duration.MEDIUM);
                            errorToast.setGravity(Gravity.CENTER, 0, 0);
                            errorToast.show();
                        }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                SuperToast.create(getActivity(), error.getMessage(), SuperToast.Duration.LONG).show();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
/*
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", uname);
                params.put("password", upass);
                return params;
            }*/
        };
        //MySingleton.getInctance(getActivity().getApplicationContext()).addToRequestQueue(rq);
        queue.add(rq);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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