CORS跨域请求,怎么将Cookie传给后端
后端
增加代码:
//CORS跨域 允许Authorization
header('Access-Control-Allow-Origin:http://wwww.demo.com');
header('Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept,Cookie');
header('Access-Control-Allow-Methods:GET,POST');
header('Access-Control-Allow-Credentials:true');//允许携带cookie
前端
demo示例:
$("#submit").click(function() {
$.ajax({
type: "POST",
url: "http://www.newweb.com/index.php?act=loginWap&op=login",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(GetJsonData()),dataType: "json",xhrFields:{withCredentials:true},crossDomain:true,success: function (data) {
if (data.code == 200) {
alert('登录成功!');
window.location.href="http://www.logindemo.com/backend.html";
}else {
alert('用户名或密码错误!');
}
},
error: function (message) {
$("#request-process-patent").html("用户名或密码错误!");
}
});
});
function GetJsonData() {
var json = {
"code": $("#code").val(),
"user_name": $("#user_name").val(),
"password": $("#password").val()
};
return json;
}
网友评论