Я пытаюсь реализовать функцию регистрации в приложении Android.
И я получаю java.net.SocketTimeoutException
ошибку:
И я получаю это с сервера Node.js:
Это не показывает никаких ошибок, но --ms--
показывает, что это заняло много времени.Другими словами, это также означает ошибку тайм-аута.
Это - routes/member.js
, где я получаю эту ошибку.
var express = require('express');
var db = require('../db');
var router = express.Router();
//member/:
router.post('/', function(req, res, next) {
console.log('/member');
console.log(JSON.stringify(req.body, null, 2));
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
console.log("email: "+email+", username: "+username+", password: "+password);
var sql = "INSERT INTO member(email, username, password) VALUES(?,?,?)";
var input = [email, username, password];
console.log("db before");
try{
console.log("db before2");
db.get().query(sql, input, function(err, res){
console.log("db");
if(err){
console.log(JSON.stringify(err, null, 2));
res.json({message:"error",code:401,result:false});
}else {
console.log(JSON.stringify(res, null, 2,));
res.json({message:"Signed up successflly.", code:100, result:true});
}
});
}catch(e){
console.log(e);
}
});
...
Я обертываю часть db
с try-catch
.Однако он ничего не перехватывает и не печатает.
И это db.js
:
const mariadb = require('mariadb');
var pool;
exports.connect = function(done){
console.log("Trying to connect DB...");
pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'simple123SNS',
database:"SimpleSNS",
connectionLimit: 5 // Why 5 ???
});
pool.getConnection()
.then(conn=>{
console.log("DB connected. id: "+conn.threadId);
conn.end(); //release to pool
}).catch(err=>{
console.log("DB failed connection: "+err);
});
}
function makeToken(){
console.log("makeToken()");
var text="";
var possible="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for(var i=0;i<32;i++){
text+=possible.charAt(Math.floor(Math.random()*possible.length));
}
return text;
}
function dbHelper(){
console.log("dbHelper()");
this.emailRequest=function(email,num){
console.log("emailRequest");
pool.getConnection()
.then(conn=>{
conn.query("INSERT INTO email_verification(email, code) VALUES(?,?)",[email,num]);
conn.end(); //release to pool
})
.catch(err=>{
console.log("not connected due to error: "+err);
});
}
this.verify=async function(email,num){
console.log("verify");
let conn;
var result=false;
try{
conn=await pool.getConnection();
// within 3minutes
const rows=await conn.query("SELECT count(*) FROM email_verificaiton WHERE email=? AND code=? AND req_time >= NOW() - INTERVAL 3 MINUTE",[email,num]);
if(rows[0]["count(*)"]>0){
result=true;
}
}catch(err){
throw err;
}finally{
if(conn)conn.end();
}
return result;
}
this.verifyUpdate=function(email,num){
console.log("verifyUpdate");
pool.getConnection()
.then(conn=>{
conn.query("UPDATE email_verification SET status = 1 WHERE email=? AND code=?",[email,num]);
conn.end(); //release to pool
})
.catch(err=>{
console.log("not connected due to error: "+err);
});
}
this.emailRegister=async function(email,pass,nick,devid){
console.log("emailRegister");
let conn;
var result;
try{
conn=await pool.getConnection();
var rows=await conn.query("SELECT count(*) FROM email_verification WHERE email=? AND status = 1",[email]);
if(rows[0]["count(*)"]>0){
rows=await conn.query("SELECT count(*) FROM member WHERE email=?",[email]);
if(rows[0]["count(*)"]==0){
var token=makeToken();
rows=await conn.query("INSERT INTO member (email,password,username,device_id,login_method,token) VALUES(?,?,?,?,0,?)",[email,pass,nick,devid,token]);
if(rows["affectedRows"]>0){
result={result:true,code:200,message:"success",data:[{email:email,token:token}]};
}else{
result={result:false,code:401,message:"db error"};
}
}else{
result={result:false,code:402,message:"already registered id"};
}
}else{
result={result:false,code:403,meesage:"email not verified"};
}
}catch(err){
throw err;
}finally{
if(conn)conn.end();
}
return result;
}
this.emailLogin=async function(email,pass,devid){
console.log("emailLogin");
let conn;
var result;
try{
conn=await pool.getConnection();
rows=await conn.query("SELECT * FROM member WHERE email=?",[email]);
if(rows.length==1){
if(rows[0]["password"]==pass){
var token=makeToken();
rows=await conn.query("UPDATE member SET device_id = ?, token = ? WHERE email=?",[devid,token,email]);
console.log(rows)
if(rows["affectedRows"]>0){
result={result:true,message:"Sign up Success.",code:200,data:[{email:email,token:token}]};
}else{
result={result:false,message:"db error",code:401};
}
}else{
result={result:false,message:"wrong password",code:402};
}
}else{
result={result:false,message:"not registered id",code:403};
}
}catch(err){
throw err;
}finally{
if(conn)conn.end();
}
return result;
}
}
exports.get=function(){
console.log("exports.get");
return pool;
}
// module.exports = new dbHelper;
Если вы видите журналы в терминале, печать заканчивается на exports.get
.Итак, я просто предполагаю, что проблема от db
.
И это app.js
:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var db = require('./db');
//var passport = require('./passport');
//var auth = require('./routes/auth');
var memberRouter = require('./routes/member');
var indexRouter = require('./routes/index');
var emailRouter = require('./routes/email');
var googleRouter = require('./routes/google');
var facebookRouter = require('./routes/facebook');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
db.connect(function(err){
console.log(err);
if(err){
console.log('Unable to connect to MariaDB.');
process.exit(1);
}
});
...
Как я могу решить эту проблему?