【问题标题】:Session handling in JQuery and node.jsJQuery 和 node.js 中的会话处理
【发布时间】:2012-01-27 17:55:24
【问题描述】:

我正在尝试将 session 与 expressjs 和 jquery 一起使用。

我有一个 node.js 服务器 @127.0.0.1:6060 使用此代码:

var Express = require('express'),
  App = Express.createServer(),
  Mongoose = require('mongoose'),
  Schema = Mongoose.Schema,
  ObjectId = Schema.ObjectId;

App.configure(function () {
  App.use(Express.bodyParser());
  App.use(Express.methodOverride());
  App.use(Express.logger({ format: '[:remote-addr] :method :url :response-time ms' }));

  App.use(Express.cookieParser());
  App.use(Express.session({ secret: "keyboard cat" }));

  // CORS
  App.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With');

    next(); 
  });
});

App.all('/api/users/test1', function (req, res) {
  req.session.test = 'toto';
  console.log(req.session.id)
  res.send({'r': req.session.id});
});
App.all('/api/users/test2', function (req, res) {
  console.log(req.session.id)
  res.send({'r': req.session.test});
});

App.listen(6060, '127.0.0.1');
console.log('App launched ...');

好的,现在如果我在浏览器中直接输入http://127.0.0.1:6060/api/users/test1 然后http://127.0.0.1:6060/api/users/test2,我会得到带有“toto”的对象结果。

但是,如果我尝试使用 jquery 1.7.1:

$.getJSON('http://127.0.0.1:6060/api/users/test1', function (json) {
    console.log(json.result);
    $.getJSON('http://127.0.0.1:6060/api/users/test2', function (json) {
        console.log(json.result)
    });
});

我在最后一次打印中得到一个空的 js 对象。 我真的不明白。有什么想法吗?

谢谢!

【问题讨论】:

    标签: jquery session node.js express


    【解决方案1】:

    说明

    $.getJSON 调用 Express 以创建新会话,因为您的链接是绝对链接 (http://...),您需要使用相对链接 ( /api/users/test1 为例)。

    解决方案

    您需要让您的应用程序在同一服务器和端口上使用 API 密钥来识别用户。

    代码

    我将使用第一个解决方案,让应用程序位于同一服务器和端口上。 在服务器上,您只需向 Express 指定您在 App.configure 中使用这样的静态目录:

    App.use(Express.static(__dirname + '/public/'));
    

    在您的 public/ 文件夹中,放入您的 index.html,其中包含:

    $.get('/api/users/test1', function (json) {
        // display something like "74V5zXFyOe0KYKG8somXUzoR.maraL4zDfFfyLfEU4W/i8eioMMK5f4+YOnUVeJO8abU"
        console.log(json.r);
        $.getJSON('/api/users/test2', function (json) {
            // display : 'toto'
            console.log(json.r)
        });
    });
    

    继续 http://localhost:6060/ 并查看控制台。

    【讨论】:

    猜你喜欢
    • 2011-12-23
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2012-12-09
    • 2014-08-05
    • 2015-01-19
    相关资源
    最近更新 更多