首页 文章

快速cookie会话不会在POST请求中保留

提问于
浏览
1

我有一个AngularJS客户端使用 $http() 函数将POST表单数据发送到Express服务器 . 我希望服务器在持有用户's email address. This is all I' m存储的客户端中设置cookie,所以我只是使用 cookie-session 模块 .

Problem: cookie未在客户端持久存在 . 来自同一客户端的后续请求显示空会话变量 .

我看到example here并在设置cookie后使用了 req.session.save() ,但它仍然无效 .

Server code:

// server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session')
var methodOverride = require('method-override');

// Configuration
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
app.use(methodOverride('X-HTTP-Method-Override'));

var express = require('express');
var app = express();

// Cookies
app.use(cookieParser());

app.use(cookieSession({
    name: 'session', // what should this name match?
    resave: true,
    saveUninitialized: true,
    keys: ['key1', 'key2']  // what do these values need to match?
}));

app.use(function(req, res, next) {
    // Create a cookie.
    console.log("Session user [before set]: %j", req.session);
    req.session.mycookie = "sample data"; // simplified example for illustration
    console.log("Session user [after set]: %j", req.session);
    // Save session cookie
    req.session.save();
});

app.listen(3000);

来自同一客户端的每个请求都会给出输出:

Session user [before set]: {}
Session user [after set]: {"mycookie":"sample data"}

客户端的后续测试显示cookie不存在 . 我甚至使用Firefox“查看Cookies”插件来检查是否创建了任何cookie,而非 .

1. Why is my cookie not persisting? 我是Express的新手,所以我可能会遗漏一些明显的东西 .

2. Am I using the correct parameters to create the cookieSession? 我不确定 keysname 应该是什么 . cookie-session documentation对此很模糊,我在其他地方找不到更好的文档 .

1 回答

  • 0

    事实证明解决方案很简单!我现在意识到 I needed to include the port number in the browser's initial request to the server (我确实在JavaScript代码中包含了端口号 . )

    即使没有端口号,浏览器也可以获得初始请求,因为同一台计算机上的另一台Web服务器(不是我的Express服务器)正在为请求提供服务 .

    只需将端口号添加到浏览器的地址栏即可 . 当然,然后我需要在服务器上添加另一个Express路由来处理站点的默认页面 . 在此之后,cookie按预期工作 .

    希望这个答案能够帮助其他Express新手 .

相关问题