项目中有一个客户端调用后端接口实现功能,其中一个功能是验证码,需要后端接口验证前端提交的验证码是否正确,客户端调用服务端的验证码,服务端验证码生成session。
ajax
ajax提交时无法保持session,如果使用的jquery ajax,则jquey提供了这个参数的设置:
$.ajax({ url: 'http://xxx.com', data: data, type: 'POST', xhrFields: { withCredentials: true }, crossDomain: true, success: function (data) { }, error: function (data) { }});
jquery ajax封装了xhr请求时的字段,需要设置“withCredentials: true”即可。
服务端响应头也要做如下变更:
'Access-Control-Allow-Origin' => $resuest->header('origin'),'Access-Control-Allow-Credentials' => 'true',
注意,当“Access-Control-Allow-Credentials”为”true”时,“Access-Control-Allow-Origin”不能设置为“*”,这里因为业务调试期间,客户端host不一定,直接设置当前请求头的“origin”即可。
附:
withCredentials的说明:
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials