【问题标题】:GET and handle data from DB with node.js express使用 node.js express 从数据库获取和处理数据
【发布时间】:2014-01-06 08:40:44
【问题描述】:

我正在创建一个 jQuery 移动应用程序,并且我有一个带有 node.js 和 express 的 linux 服务器。我认为身份验证工作正常,并且与另一个数据库服务器的数据库连接也是如此。

我的问题是,我不知道如何在客户端从我的服务器接收和处理数据。 任何人都可以通过提供一些代码 sn-p 或其他东西来帮助我做到这一点吗?例如,我如何获取和处理数据以及如何添加预订?

我的 node.js 快速服务器上的 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)
})

【问题讨论】:

  • 您究竟想在哪些页面上显示什么?据我所知,您只能查看 2 个页面 /getLata 和 /addReservation。问题是您没有使用res.send("some JS object Data") 或以任何方式发送数据“FromDB”。另外,它不会被样式化,它将是纯 JSON 数据。
  • getLata:我想在我的 jQuery 移动页面上显示所有 pid=1 的地段。并且使用 addReservation,我想在单击按钮后的特定时间保留很多 :)

标签: javascript jquery json node.js express


【解决方案1】:

对于使用 node 和 express 的服务器端身份验证,您可以参考并参考流行的护照模块。查看他们的示例,类似于您在 https://github.com/jaredhanson/passport-local/tree/master/exampleshttp://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 );
});

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2016-10-26
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多