【发布时间】:2021-06-24 09:10:45
【问题描述】:
我正在尝试在 node.js 中实现 HTTP 服务器。我想做以下事情:
- 从客户端应用程序接收注册请求;
- 尝试将用户添加到服务器的数据库中;
- 通知客户端应用注册是否成功(例如,由于用户名可能重复)。
这是我目前拥有的代码:
request.on('end', () => {
if (!this.checkLevel())
return;
const username = this.json_data.username;
const full_name = this.json_data.full_name;
const new_user_lvl = this.json_data.new_user_lvl;
const oid = this.generateOID(12);
database.addUser(username, full_name, new_user_lvl); //code below
database.addValidOID(oid, username);
const body = oid;
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
});
response.end(body);
});
//database.addUser
function addUser(username, full_name, clearance_lvl)
{
const db = new sqlite3.Database(DB_PATH + DB_NAME);
const stmt = db.prepare("INSERT INTO User(username, full_name, clearance_lvl) VALUES (?,?,?)");
stmt.run(username, full_name, clearance_lvl, function (err){
if (err) throw err;
console.log(`[Database] Added New User (${username})`);
});
stmt.finalize();
db.close();
}
鉴于当前的代码,我不知道如何捕捉addUser 生成的异常以相应地创建我的http 响应。我已经尝试用try/catch 块包围addUser,但没有效果。有人可以帮我解决这个问题吗?
【问题讨论】:
标签: javascript node.js database sqlite http