Angular.js与node.js项目里用cookie校验账户登录详解(2)

在查阅了一段时间后了解到,客户端是会默认携带cookie给服务端的,但是当客户端的请求是跨域请求时,由于跨域请求本身就有风险,而携带给cookie同样有风险。

因此在进行跨域访问时,客户端不会将服务端返回的cookie携带。此时,我们需要同时在客户端和服务端都设置“withCredentials”为true,代码如下:

// client $http({ method : 'POST', url : 'http://127.0.0.1:8888/rest/user', withCredentials: true data : {name: 'xxx',password:'***'} }).success(function (data) { console.log('login success,data is:'+data); }).error(function (data) { console.log('login error'); }).then(function () { console.log(arguments); }); // server var cookie = "authId=" + authId; res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.setHeader('Set-Cookie', cookie + ';Max-Age=3600;HttpOnly=false;Path=https://www.jb51.net/;'); // 添加允许跨越的头信息 res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); // 添加支持Content-Type允许的头信息 res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // 设置已携带凭证为true //res.setHeader('Access-Control-Allow-Credentials', true); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end();

运行后,发现又有错误提示,如下:

Angular.js与node.js项目里用cookie校验账户登录详解

XMLHttpRequest cannot load :8888/rest/user. Response to preflight request doesn't pass access control check: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:62427' is therefore not allowed access.

分析错误后发现,原因是当设置了已携带凭证参数为true时,允许跨域请求的源不能设置为泛型的“*”,因此我们再次修改代码如下:(最终代码)

// client $http({ method : 'POST', url : 'http://127.0.0.1:8888/rest/user', withCredentials: true data : {name: 'xxx',password:'***'} }).success(function (data) { console.log('login success,data is:'+data); }).error(function (data) { console.log('login error'); }).then(function () { console.log(arguments); }); // server var cookie = "authId=" + authId; res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.setHeader('Set-Cookie', cookie + ';Max-Age=3600;HttpOnly=false;Path=https://www.jb51.net/;'); // 添加允许跨越的头信息 // res.setHeader('Access-Control-Allow-Origin', '*'); // 用当前的客户端origin来取代泛型的“*” res.setHeader('Access-Control-Allow-Origin', 'http://localhost:62427'); res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); // 添加支持Content-Type允许的头信息 res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // 设置已携带凭证为true res.setHeader('Access-Control-Allow-Credentials', true); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end();

此时,第一次请求服务端时,服务端返回cookie信息,以后每次客户端请求服务端,客户端的header中都会携带cookie信息,效果如下图:

Angular.js与node.js项目里用cookie校验账户登录详解

最后

以上就是在使用cookie记住用户身份时遇到的一些问题及简单解决方法,一般在angular应用中,可能使用较多的是resoure进行http通信,此时只要在GET/POST/PUT/DELETE等请求的参数中,将“withCredentials”设置为true即可。希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzxdj.html