1. 前后端分离解决跨域问题
解决跨域调用服务并设置headers 主要的解决方法需要通过服务器端设置响应头、正确响应options请求,正确设置 JavaScript端需要设置的headers信息 方能实现;
关于跨域,前端会先发送OPTIONS请求,进行预检,检查后端是否允许前端设置的相应的请求头,请求内容
functiongetCookie(name) {var cookieValue = null;if (document.cookie && document.cookie != '') {var cookies = document.cookie.split(';');for (var i = 0; i < cookies.length; i++) {var cookie =jQuery.trim(cookies[i]);//Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue= decodeURIComponent(cookie.substring(name.length + 1));break;
}
}
}returncookieValue;
}var csrftoken = getCookie('csrftoken');functioncsrfSafeMethod(method) {//these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain:false, //obviates need for sameOrigin test
beforeSend: function(xhr, settings) {if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
官方js解决csrf
- 浏览器error: 添加了官方解决csrftoken的js代码后,报跨域错误
Failed to load http://127.0.0.1/course/api/signup/che