JQuery和node.js中的会话处理
我正在尝试使用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 ...');
好的,现在如果我在浏览器中直接inputhttp://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对象。 我真的不明白。 任何想法?
谢谢!
吃茶
$.getJSON
调用Express来创build一个新的会话,因为你的链接是绝对的( http:// … ),你需要用相对链接(例如/ api / users / test1 )来调用你的服务器。
解
您需要将您的应用程序放在同一台服务器和端口上, 或使用API密钥来识别用户。
码
我将使用第一个解决scheme,将应用程序放在同一台服务器和端口上。 在服务器上,你只需要指定在你的App.configure
使用这样的静态目录:
App.use(Express.static(__dirname + '/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 /看看控制台。