js创建cookie时获取一级域名设置domain解决跨域问题

提醒:本文最后更新于 2890 天前,文中所描述的信息可能已发生改变,请仔细核实。

最近一个项目,Chatbox(博客右下角),就遇到这个问题。

所以写了个js函数解决这个问题。

function GetCookieDomain() {
 var host = location.hostname;
 var ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
 if (ip.test(host) === true || host === 'localhost') return host;
 var regex = /([^]*).*/;
 var match = host.match(regex);
 if (typeof match !== "undefined" && null !== match) host = match[1];
 if (typeof host !== "undefined" && null !== host) {
  var strAry = host.split(".");
  if (strAry.length > 1) {
   host = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1];
  }
 }
 return '.' + host;
}

支持本地环境(仅判断localhost)、host为ip地址、中文域名、常规域名。如下所示:

输入 输出
127.0.0.1 127.0.0.1
192.168.1.1 192.168.1.1
localhost localhost
255.255.255.256 .255.256
kn007.net .kn007.net
info.kn007.net .kn007.net
a.b.c.d.e.f.1.2.3.4.5.kn007.net .kn007.net
中文.中国 .中文.中国
在此.祝你.春节.快乐 .春节.快乐

调用很简单,写了个示例:

document.cookie = cname + "=" + cvalue + "; expires=" + expires + "; domain=" + GetCookieDomain() + "; path=/";

说解决跨域,其实只是解决子域和主域的cookie问题。

这项目是朋友ArchiTech创建的,项目地址传送门,欢迎大家Fork和PR。

当练习nodejs和js了。。。当然最重要的是写中英文档,练手。

其中得到比较重要的启发是:Websocket最好运行在SSL状态,快,而且同端口完成连接握手通讯。

通过80反代后端应用端口,容易出现:

failed: Error during WebSocket handshake: Unexpected response code: 400

资料:

This is almost always due to not using https (SSL).
Websocket over plain http is vulnerable to proxies in the middle (often transparent) operating at the http layer breaking the connection.
The only way to avoid this is to use SSL all the time - this gives websocket the best chance of working.
More info at subsection 4.2.1 of the WebSockets RFC 6455.

[Test]Scheduled post via WordPress 4.2.2 from kn007's blog.

转载请注明转自:kn007的个人博客的《js创建cookie时获取一级域名设置domain解决跨域问题