我正在创建一个 jQuery 移动应用程序,我有一个带有 node.js 和 express 的 linux 服务器。我认为身份验证工作正常,并且与另一个数据库服务器的数据库连接也是如此。
我的问题是,我不知道如何在客户端接收和处理来 self 的服务器的数据。 任何人都可以通过提供一些代码片段或其他内容来帮助我做到这一点吗?例如,我如何获取和处理数据以及如何添加预订?
我的 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
在客户端,在用户通过身份验证后,用户通常会有一个 session cookie,该 cookie 将随每个请求一起发送。服务器端的 isAuthenticated 方法将确认此 session 有效,然后处理请求。 session cookie 由浏览器自动发送到同一域中的服务器。
要在验证后获取数据,您可以使用 jQuery 发送类似于以下内容的 ajax 请求:
$.get( "getLata", function( data ) {
$( ".result" ).html( data );
});
要添加预订,您应该认真考虑更改服务器端路由以接受 POST 而不是 GET 请求,因为您正在修改数据。使用 jQuery 的客户端 ajax 帖子看起来类似于:
$.post( "addReservation", {lot_id: "123"}, function( data ) {
$( ".result" ).html( data );
});
关于javascript - 使用 node.js express 从数据库获取和处理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20904144/