php 前后端分离开发进行跨域请求时ajax发送验证参数token的header头解决方法

php 前后端分离开发进行跨域请求时ajax发送验证参数token的header头解决方法

php前后端分离开发中要实现前后端参数信息交互,必须解决token标识验证问题。

步骤如下:

1.前端ajax发送请求时,要设置一个自定义header头。代码如下:

$.ajax({
url:”http://www.xxx.com/接口方法”,
type:”get”, //请求方式
dataType:”JSON”, //请求参数格式
data:{id:1,abc:12}, //请求参数
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader(‘Token’, ‘qwertyuuui’); //自定义header头

// XMLHttpRequest.setRequestHeader(自定义header头名称, 参数值);其中参数值可以为json字符串
},
contentType: ‘application/json’,
success: function(data){
alert(‘成功’+data);
},
error : function(jqXHR) {
alert(‘失败’+jqXHR.status);
}
})

2.后端php接收header数据 代码如下:

public funtion 接口方法名称 {
if($_SERVER[‘REQUEST_METHOD’] == ‘OPTIONS’){
// 解决预请求OPTIONS
header(‘Access-Control-Allow-Origin:http://runapi.showdoc.cc’);
header(‘Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,Token’);
header(‘Access-Control-Allow-Credentials:true’);
header(‘Access-Control-Allow-Methods:GET,POST,OPTIONS’);
header(‘Access-Control-Max-Age:1728000’);
header(‘Content-Type:text/plain charset=UTF-8’);
header(‘Content-Length: 0’, true);
header(‘status: 200’);
header(‘HTTP/1.0 204 No Content’);
exit;
}else{
// 获取ajax请求header
header(‘Access-Control-Allow-Origin:http://runapi.showdoc.cc’); //允许跨域请求的域名
header(‘Access-Control-Allow-Credentials: true’);
header(“Access-Control-Allow-Methods:GET, POST, PUT,DELETE,POSTIONS”); // 允许跨域请求的方式
header(“Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie,Token“); // 将前端自定义的header头名称写入,红色部分
}

//获取自定义Token的值 以tp5.1接收方式为例。

$token = Request::header(‘Token‘);

dump($token);

}

注:

1.当token发送成功时,F12浏览器在NetWork下的文件中header内会有Token。如下图所示

php 前后端分离开发进行跨域请求时ajax发送验证参数token的header头解决方法

2.自定义的header头的请求参数可以自己设置,若为数组或者对象,请转化为json字符串

Intoep小程序

微信扫一扫,打开小程序浏览更便捷

转载作品,原作者:,文章来源:https://blog.csdn.net/pyp_demon/article/details/84166502

发表回复

登录后才能评论