使用$ .ajax({})时,Express Session不保存;
正如它所说。 我试图将一些数据保存为一个Express会话,Express似乎将每个AJAX请求视为一个单独的会话,因此不保存我的数据。
在客户端
$.ajax({ url: '/orders', method: 'post', data: { item: item } });
在服务器上
router.post('/orders', function(req, res) { var sess = req.session, order = sess.order || [], item = req.body.item || '', quantity = req.body.quantity || 1; if (!item) return res.status(404).end(); if (order[item]) { order[item] += quantity; } else { order[item] = quantity; } //save our order to the session req.session.order = order; req.session.save(); console.log(req.session.order); // verified that req.session.order is set return res.status(200).end(); });
这不是一个CORS请求 – 这是我从本地运行的客户端打到我的本地服务器。
将下面的代码添加到你的$.ajax
configuration可能会解决这个问题:
$.ajax({ xhrFields: { withCredentials: true }, ... // other settings })
使用fetch为我工作,如下所示
fetch(url, { credentials: 'include', method: 'post', ...// other fetch configs }).then(onsuccesscallback)
关键是在configuration抓取时包括凭据