I am trying to use session with expressjs and jquery.
I have a node.js server @127.0.0.1:6060 with this code :
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 ...');
Ok, now if I directly enter http://127.0.0.1:6060/api/users/test1 then http://127.0.0.1:6060/api/users/test2 in my browser, I get my object result with ‘toto’.
However, if I try with 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)
});
});
I get an empty js object in the last print.
I really do not understand. Any idea?
Thank you!
Explications
$.getJSONcall to Express to create a new session because your link is absolute (http://…), you need to call your server with a relative link (/api/users/test1 for exemple).Solution
You need to have your application on the same server and port or use an API key to recognize the user.
Code
I’ll use the first solution, to have the application on the same server and port.
On the server, you just need to specify to Express that you use a static directory like this in your
App.configure:In your public/ folder, put your index.html which contains :
Go on http://localhost:6060/ and look the console.