Javascript Express使用页面向用户发送信息
我有以下代码Javascript Express使用页面向用户发送信息,javascript,node.js,express,Javascript,Node.js,Express,我有以下代码 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{ //IMPORTA
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');
}
});
}
不要担心数据库的事情
我想知道如何将req.params.uid发送到客户端,以及如何从客户端获取它
非常感谢。根据我的评论,这只是一个更完整的答案 如果您希望在用户发出的每个请求中存储有关用户的字符串信息,那么您希望使用 当用户第一次向页面发出请求时,您可以通过设置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
但是,您需要事先在应用程序中的某个位置安装中间件:
var cookieParser = require('cookie-parser');
app.use(cookieParser());
如果需要访问客户端上的uid
值,可以使用模板,或者在使用res.cookie
设置时将httpOnly
值设置为false
。然后您可以使用访问cookie
在客户端上查看访问cookie的信息 如果用户配置正确,则每个请求都会有一个用户:
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发送。检查这些以发送cookie并在将来的请求中获取它。您的问题有点模糊,您是在问如何向客户端发送req.params.uid吗?如果这是一个问题,req.params.uid
意味着它已经从客户端发送。请尝试使用此返回response.render('yourview',req.params.uid)如果这不正确,那么是的,你的问题太模糊了。也许你正在尝试使用像Jade或EJS这样的服务器模板引擎..谢谢这帮助了我堆积了我所需要的东西。你能接受它作为答案吗。谢谢
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)
}
});