首先描述下出现跨域问题的情况
以下几种情况可能会有跨域问题:
1、协议不同,例如: http…https
2、ip不同,例如localhost、、127.0.0.1、、你的本机IP(例如:192.168.12.xxx)
3、端口(8080、、9003)
这些都可能会导致跨域问题。
我在做的这个项目,整个项目前后端都是靠sessionID会话的,如果我给你返回的session你不带回来的话,我会认为你是个新人,你是一个新的sessionID,你的ID和我的ID不一样的所以本次会话到此结束。
而浏览器知道你在跨域的时候 他是不会自己带cookie的(不跨域的情况下,带cookie是浏览器的默认行为)。
温馨提示
请仔细阅读代码块中的注释,不要着急跳过哦
jQuery解决跨域问题:
AjaxAction.prototype.appendToken = function (url) {
return url;
}
// 预处理返回的数据,防止后台服务不在线时,返回不合法数据
AjaxAction.prototype.preHandleResult = function (data) {
if (data && (!data.hasOwnProperty('error') || typeof data.error != "number")) {
data.error = 404;
data.description = "后台服务异常,请联系管理员";
}
}
// 如果发同步请求,把async形参值改为false即可
AjaxAction.prototype.get = function (url, jsondata, success, error, async = true, traditional = false) {
$.ajax({
type: "get",
url: this.appendToken(url),
data: jsondata,
dataType: "json",
traditional: traditional,
async: async,
// 允许请求携带cookie
xhrFields: {
withCredentials: true
},
success: function (data) {
this.preHandleResult(data);
if (data.error == 0) {
success(data.value);
} else {
error && error(data);
console.log(`请求:${url}`);
console.log(`错误:${data.description}`);
if (error == null) showErrorTip(data.description);
}
}.bind(this),
error: function (data) {
this.preHandleResult(data);
error && error(data);
}.bind(this)
});
}
这样写上后,你就会发现就算跨域了,浏览器不带,你的请求消息头也会带cookie的。nice成功解决跨域问题!