使用node.jsexpression式获取和处理来自数据库的数据

我正在创build一个jQuery移动应用程序,并且我有一个带有node.js和express的linux服务器。 我认为authentication工作正常,并与另一个数据库服务器的数据库连接。

我的问题是,我不知道如何接收和处理客户端从我的服务器的数据。 任何人都可以帮助我做到这一点,通过给一些代码片段或别的东西? 我怎样才能获得和处理数据,我怎样才能添加一个预订例如?

我的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的服务器端身份validation,您可以参考并引用stream行的护照模块。 看到他们的例子,类似于你正在尝试在https://github.com/jaredhanson/passport-local/tree/master/examples和http://passportjs.org

在客户端,用户通过身份validation后,用户通常会有一个会随每个请求一起发送的会话cookie。 服务器端isAuthenticated方法会确认这个会话是有效的,然后处理请求。 会话cookie由浏览器自动发送到同一个域的服务器。

为了获得authentication后的数据,可以使用jQuery发送类似于以下内容的ajax请求:

 $.get( "getLata", function( data ) { $( ".result" ).html( data ); }); 

要添加预留,您应该强烈考虑将服务器端路由更改为接受POST而不是GET请求,因为您正在修改数据。 使用jQuery的客户端ajax后,看起来类似于:

 $.post( "addReservation", {lot_id: "123"}, function( data ) { $( ".result" ).html( data ); });