当处理非简单请求时,客户端会向服务端发送 OPTIONS
的预请求,CodeIgniter4 本身没有对这个方法提供支持,这导致我们一些需要验证参数的方法可能会返回异常,例如
Access to XMLHttpRequest at 'http://localhost/api/login' from origin 'http://localhost:8010' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
但是我们可以借助其他手段,来达到这个目的。
我们在编辑 Controller
时,一般都会继承一个父类,该功能我们在继承的这个父类中实现。
<?php namespace App\Controllers;
use CodeIgniter\Controller;
class BaseController extends Controller
{
public function _remap($method)
{
if('options' !== strtolower($this->request->getMethod())){
return $this->$method();
}
}
}
_remap
方法会在 Controller
实例化后 method
执行前进行调用,我们可以在函数中判断当前请求的 method
,进而拦截 options
请求。这样就不会真的执行具体方法,也就不会进行具体的业务流程。