Express通过页面向用户发送信息

Express send information to user with a page

本文关键字:信息 面向用户 Express      更新时间:2024-06-30

我有以下代码

var user = function(req,res,next) {
db.findOne({ username: req.params.uid }, function (err, docs) {
//error handaling
if(err){console.log(err)}
//check if user is real
if(docs === null){
     res.end('404 user not found');
}else{
    //IMPORTANT PART res.sendFile(__dirname + '/frontend/user.html');
    }
});

}

app.get('/user/:uid',user);

不要担心数据库的东西。

我想知道如何将req.params.uid发送到客户端,以及如何从那里获得它。

非常感谢。

如果您的用户配置正确,每个请求都将有一个用户:

var user = function(req,res) {
db.User.findOne({ _id: req.user._id }, function (err, docs) {
//error handaling
if(err){console.log(err)}
//check if user is real
if(docs === null){
     res.end('404 user not found');
}else{
    res.json(docs)
    }
});

然后你的api端点就是'/user/

在您的客户端中,只需向该端点发出GET请求(可能使用AJAX),您的响应将是发出该给定请求的任何用户。

注意:除非定义中间件,否则不需要传入next

这只是基于我的评论的一个更完整的答案。

如果你想在用户提出的每个请求中存储一系列关于用户的信息,那么你就需要使用cookie。

当用户第一次向页面发出请求时,您将通过res.cookie设置cookie。因此,在您的代码中,最后的if语句看起来像:

if(docs === null) {
    res.end('404 user not found');
} else {
    res.cookie('uid', req.params.uid, { httpOnly: true });
    //IMPORTANT PART res.sendFile(__dirname + '/frontend/user.html');
}

然后,在cookie到期前的下一个请求和未来请求中,您可以使用访问它

req.cookies.uid

然而,您需要预先在应用程序中的某个位置安装cookie-parser中间件:

var cookieParser = require('cookie-parser');
app.use(cookieParser());

如果需要在客户端访问uid的值,可以使用模板,也可以在使用res.cookie设置httpOnly时将其设置为false。然后您可以使用document.cookies访问cookie

查看此W3Schools页面以访问客户端上的cookie。