跨域请求-JWT认证将token添加到Authorization
后端
增加代码:
header('Access-Control-Allow-Origin:
header('Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept,Authorization');
header('Access-Control-Allow-Methods:GET,POST');
//CORS跨域 允许Authorization
header('Access-Control-Allow-Origin:http://wwww.demo.com');
header('Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept,Authorization');
header('Access-Control-Allow-Methods:GET,POST');
前端
增加代码:
beforeSend: function(xhr) {
var token = 'xxxxxxxxxx';
xhr.setRequestHeader("Authorization", "Bearer "+token);
},
demo示例:
$("#submit").click(function() {
$("#request-process-patent").html("正在提交数据,请勿关闭当前窗口...");
$.ajax({
type: "POST",
beforeSend:function(xhr){
var token='xxxxxxxx';xhr.setRequestHeader('Authorization','Bearer '+token);},url: "http://www.newweb.com/index.php?act=loginWap&op=login",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(GetJsonData()),
dataType: "json",
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;
}
网友评论