028-86261949

当前位置:首页 > 技术交流 > Thinkphp5中实现Restful接口ajax发起PUT或DELETE无法跨域

Thinkphp5中实现Restful接口ajax发起PUT或DELETE无法跨域

2019/05/31 10:29 分类: 技术交流 浏览:1

问题一: 
在Thinkphp5中实现Restful接口规范,根据官方文档在 route.php 中设置了路由:
Route::resource('Rest','api/Rest');

因为接口都需要跨域调用,也设置了跨域响应头:
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE, HEAD');
header('Access-Control-Allow-Headers:X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept');

在客户端使用ajax发起GET或POST请求时,可以实现跨域。而发起PUT或DELETE请求时会报错,无法跨域。


ajax.js:12 OPTIONS http://tp5.com/rest/10.html 404 (Not Found)
index_rest.html:1 Access to XMLHttpRequest at 'http://tp5.com/rest/10.html' from origin 'http://127.0.0.1:8020' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

问题原因:
GET和POST请求是简单请求,AJAX只发起一次,所以设置了响应头和路由就可以实现。
而PUT和DELETE等请求是复杂请求,会提前发起一个 OPTIONS 预请求,再发起PUT或DELETE请求,一共会发起两次请求。


问题解决:
需要在route.php路由配置文件中再添加 OPTIONS 请求的单独处理。
Route::resource('Rest','api/Rest');
Route::rule('Rest/:id','api/Rest/update', 'OPTIONS'); 


另外,接口可以使用COOKIE或SESSION,但是跨域时无法使用COOKIE。

 

#标签:Thinkphp5,Restful,ajax,PUT DELETE,无法跨域