使NodeJS功能同步?在查询数据库之前发送json响应

时间:2017-11-24 04:43:14

标签: java android node.js rest express

我正在使用nodejs作为后端语言进行登录/注册Android应用程序UI。发生的事情是每当我点击注册按钮时,它会在查询数据库之前发送json响应(select语句检查用户名是否存在)导致android应用程序得到错误的响应,这导致我点击按钮两次以注册正确响应。例如,假设他们是数据库中名为test的用户名,我尝试使用用户名test进行注册,它会告诉我用户名已被占用,如果擦除测试并输入,请说“bob'数据库中不存在它仍然表示用户名已经被占用,即使它不是,但当我再次单击注册按钮时,它将注册用户。我假设这是发生的,因为它是异步的(它在查询数据库时或之前发送json响应)。我如何进行此同步或是否有其他方法来解决此问题?

服务器文件:

var express = require('express');
var app  = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');

//connection
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "password",
    database : "androidtest"
});

//use json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//declare variables to hold values entered by the user
var name;
var username;
var password;
var age;

//boolean array to let frontend know what is going on
var response;

app.post('/', function(req, res) {
    //retrieve variables
    username = req.body.username;
    name = req.body.name;
    age = req.body.age;
    password = req.body.password;

    //query database
    //check if username is taken
    var select = "SELECT * FROM users WHERE username = ? LIMIT 1";
    con.query(select, [username], function (err, results) {
        if (err) throw err;
        //if username is taken send json string 'exists' to android app
        if(results.length) {
            response = {"exists" : "true"};     
        //if username is available send string 'success' and add the user to the database
        } else {
            var add = "INSERT INTO users (name, username, age, password) VALUES (?, ?, ?, ?)";
            response = {"success" : "true"};
            con.query(add, [name, username, age, password]);
            if (err) throw err;
            console.log('row inserted');
        }
    });
    //send json
    res.json(response);
    //prevents the functions from being executed more than once
    res.end('/');
});
//listen on port 3000
app.listen(3000);

android app java:

bRegister.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        final String name = etName.getText().toString();
        final String username = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        final int age = Integer.parseInt(etAge.getText().toString());

        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    //Boolean exists = jsonResponse.getBoolean("exists");
                    String exists = jsonResponse.getString("exists");
                    if (exists.matches("true")) {
                        Toast toast = Toast.makeText(getApplicationContext(), "username already exists", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    //Boolean success = jsonResponse.getBoolean("success");
                    String success = jsonResponse.getString("success");
                    if (success.matches("true")) {
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        RegisterActivity.this.startActivity(intent);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                        builder.setMessage("Register Failed")
                                .setNegativeButton("Retry", null)
                                .create()
                                .show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
        RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
        queue.add(registerRequest);
    }
});

}

1 个答案:

答案 0 :(得分:0)

你必须把

res.json(...);
res.end('/');

在以下行的关闭bracker之后(在else块之外和之后):

console.log('row inserted');

然后它首先在查询结束时执行。