最近在学习 express, 就用以前做的项目来进行 express 前后端分离的练手了, 在做登陆注册的时候发现跨域的时候, session 的值是会失效的, 导致 session 里面的数据获取为 undefined, 网上找资料加上自己的不断尝试, 终于找到了解决方法, 简单记录一下解决方法.
1, 客户端因为 session 原则上是需要 cookie 支持的, 所以 Ajax 方法里面必须添加 xhrFields:{withCredentials:true}, 表示允许带 Cookie 的跨域 Ajax 请求 ( 特别说明, 只要使用的 session 都得加这句)
- $('#login').click(function () {
- $.Ajax({
- url: 'http://localhost:3000/users/yzm',// 服务端路由地址
- type: 'get',
- xhrFields:{withCredentials:true},
- dataType: 'json',
- success:function(data){
- $('#yzm_img').html(data)
- },
- error:function(){
- alert('error');
- }
- });
- });
- $('#form_login').submit(function (e) {/!* 登录 *!/
- e.preventDefault();/!* 阻止表单默认事件, 页面全局刷新 *!/
- var data=$('#form_login').serialize();/!* 将表单里的数据包装起来 *!/
- $.Ajax({
- url : 'http://localhost:3000/users/login',
- type : "post",
- data : data,
- xhrFields:{withCredentials:true},
- dataType:'json',
- success:function(msg) {
- alert("这是返回的数据"+msg);
- },
- error:function(err){
- alert("这是失败的信息"+err);
- }
- });
- });
通过设置 withCredentials: true , 发送 Ajax 时, Request header 中便会带上 Cookie 信息.
2, 服务器端修改 App.JS 文件
相应的, 对于客户端的参数, 服务器端也需要进行设置.
对应客户端的 xhrFields.withCredentials: true 参数, 服务器端通过在响应 header 中设置 Access-Control-Allow-Credentials = true 来运行客户端携带证书式访问. 通过对 Credentials 参数的设置, 就可以保持跨域 Ajax 时的 Cookie.
- var express = require('express');
- var session = require('express-session');/* 引入会话变量 */
- var App = express();
- App.all('*', function(req, res, next) {
- res.header("Access-Control-Allow-Origin", "http://localhost:63342");// 前端域名
- res.header("Access-Control-Allow-Credentials",'true');
- res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
- next();
- });
特别注意: 服务器端 Access-Control-Allow-Credentials = true 时, 参数 Access-Control-Allow-Origin 的值不能为 '*' , 必须为自己客户端项目所在地址.
3, 服务器中使用 session
- router.get('/yzm', function(req, res, next) {
- req.session.yzm='abcd';
- }
- router.post('/login', function(req, res, next) {
- console.log(req.session.yzm);
- }
来源: https://www.cnblogs.com/xyyl/p/11053790.html