[英]GET and handle data from DB with node.js express
我正在创建一个jQuery移动应用程序,并且有一个具有node.js和express的linux服务器。 我认为身份验证工作正常,并且数据库与另一个数据库服务器的连接也很好。
我的问题是,我不知道如何从客户端的服务器接收和处理数据。 有人可以通过提供一些代码片段或其他方式帮助我做到这一点吗? 例如,如何获取和处理数据?如何添加保留?
我的node.js Express服务器上的auth.js:
/* ************ Authentication ************ */
app.post('/auth', function(req, res) {
var user = req.body.user;
var password = req.body.password;
DoIfAuthenticated(function (){
res.send(200);
console.log("Authenticated - Sending 200");
},req,res)
});
function DoIfAuthenticated(isAuth, req, res){
Authenticated(isAuth, function(){
res.send(406);
console.log("User not authenticated");
}, req)
}
function Authenticated(isAuth, isNotAuth, req){
db.serialize(function(){
var stmt = db.prepare("select password from users where name like ?");
stmt.get(req.body.user, function(err, row) {
if(row == undefined){
isNotAuth();
console.log("User not exists");
return;
}
if(row.password !== req.body.password){
isNotAuth();
console.log("Wrong password");
}else{
isAuth();
console.log("Successful");
}
});
})
}
/* ************************ */
app.get('/getLata', function(req, res){
DoIfAuthenticated(function() {
getFromDB("select * from lots where pid = " + req.param("gara"), req, res)
}, req, res)
})
app.get('/addReservation', function(req, res){
DoIfAuthenticated(function() {
getFromDB("insert into reservation (p_lot_id, start_time, end_time)" +
"values ("+ req.param("lot") +", TIMESTAMP '" + req.param("start") + "', " +
"TIMESTAMP '" + req.param("end") + "')", req, res)
}, req, res)
})
对于使用node和express的服务器端身份验证,您可以参考并参考流行的通行证模块。 查看他们的示例,类似于您在https://github.com/jaredhanson/passport-local/tree/master/examples和http://passportjs.org尝试的示例
在客户端,在对用户进行身份验证之后,用户通常将拥有一个会话cookie,该会话cookie将随每个请求一起发送。 服务器端的isAuthenticated方法将确认此会话有效,然后处理该请求。 会话cookie由浏览器自动发送到同一域中的服务器。
要在身份验证后获取数据,可以使用jQuery发送类似于以下内容的ajax请求:
$.get( "getLata", function( data ) {
$( ".result" ).html( data );
});
要添加预留,在修改数据时,您应该强烈考虑将服务器端路由更改为接受POST而不是GET请求。 使用jQuery的客户端ajax帖子看起来类似于:
$.post( "addReservation", {lot_id: "123"}, function( data ) {
$( ".result" ).html( data );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.