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 如下圖所示
2.自定義的header頭的請求參數可以自己設置,若為數組或者對象,請轉化為json字符串