gpt4 book ai didi

java - 使 Node JS 功能同步?在查询数据库之前发送json响应

转载 作者:太空宇宙 更新时间:2023-11-04 01:57:09 26 4
gpt4 key购买 nike

我正在使用nodejs作为后端语言制作登录/注册android应用程序UI。发生的情况是,每当我单击注册按钮时,它都会在查询数据库之前发送 json 响应(选择语句来检查用户名是否存在),导致 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);

安卓应用程序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);
}
});

}

最佳答案

你必须把

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

在以下行的结束括号之后(在 else block 之后和外部):

console.log('row inserted');

然后当查询完成时它首先被执行。

关于java - 使 Node JS 功能同步?在查询数据库之前发送json响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466490/

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