如何从function.js中的express和node js访问会话变量 [英] how to access session variables from express and nodes js in function.js

查看:112
本文介绍了如何从function.js中的express和node js访问会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够设置和访问会话变量,例如req.session.t1等,并且在服务器端都可以正常工作.在客户端,我在前端安装了jquery并可以通过jade模板进行访问.

I am able to set and access session variables, like req.session.t1, etc. and all works fine on server side. On client side I have jquery installed on the front end and accessed by jade template.

我在functions.js中使用

I have in functions.js:

$(function(){          

    var t1 = req.session.t1;      

    $('.results').append(t1); 

});         

因此,在加载页面/jade模板时,如果我使用常量或字符串,jquery会按概述将数据追加,但如果使用req.session.x或session.x,则会话变量是未定义的.

So as page/jade template loads, jquery does append the the data as outlined IF I use constants or a string, but session variables are undefined if I use req.session.x or session.x.

问题是,我如何才能最好地通过jQuery,会话变量进行操作?还是我需要保存到数据库并将其每次拉起?我是新手,不知道如何在节点js和express和jquery中做到这一点.

So question is, how would I best be able to manipulate via jQuery, session variables? Or do I need to save to DB and pull it up each time? I'm newbie and not sure how to do this in node js and express and jquery.

推荐答案

Node.js/express在服务器上运行.

Node.js/express run on the server.

jQuery在客户端上运行.

jQuery runs on the client.

共享的唯一内容是您发送给客户端的任何内容.

The only thing that's shared is whatever you've sent to the client.

如果希望变量可以在客户端访问,则需要在响应中发送它.

If you want a variable to be accessible client-side, you need to send it in the response.

如果您要退还服务器JSON,只需添加一个字段即可.

If you're giving the server JSON back, just add a field.

res.send({t1: req.session.t1}); // (node.js side)

如果要输出模板,则可以在HTML标签中或直接在脚本标签中编写.

If you're outputting a template, you can write it in a HTML tag, or directly in a script tag.

玉的例子:

script. // .jade file
  var t1 = "#{t1}"

在服务器中:

res.render('template.jade', {t1: req.session.t1});

这篇关于如何从function.js中的express和node js访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆