【发布时间】:2023-03-03 05:49:21
【问题描述】:
我正在使用 CakePHP 3 开发一个 REST API。我想公开启用它,这样任何人都可以调用 API。 因此,我添加了此处定义的 cors 标头:http://book.cakephp.org/3.0/en/controllers/request-response.html#setting-cross-origin-request-headers-cors
我已经在 Dispatcher.beforeDispatch 和 Dispatcher.beforeDispatch 上实现了 EventListener 来准备 cors 标头。
class ApiResponseHeaders implements EventListenerInterface
{
/**
* Event bindings
*
* @return array
*/
public function implementedEvents()
{
return [
'Dispatcher.beforeDispatch' => [
'callable' => 'beforeDispatch',
'priority' => 0
],
'Dispatcher.afterDispatch' => [
'callable' => 'afterDispatch',
'priority' => 99999
]
];
}
public function beforeDispatch(Event $event)
{
$request = $event->data['request'];
if ('OPTIONS' === $request->method()) {
$event->stopPropagation();
}
}
public function afterDispatch(Event $event)
{
$request = $event->data['request'];
$response = $event->data['response'];
$response->cors($request)
->allowOrigin('*')
->allowMethods(['GET', 'POST', 'OPTIONS'])
->allowHeaders(['Content-Type, Authorization, X-Requested-With, Accept'])
->allowCredentials()
->maxAge(0)
->build();
if ('OPTIONS' === $request->method()) {
$event->stopPropagation();
}
}
}
但问题是,当我从 AngularJS 向 API 端点发出 POST 请求时,它首先调用 OPTIONS 方法,然后调用 POST 方法。 CakePHP 不处理 OPTIONS 方法调用并返回:400 Bad Request
以下是示例请求和响应标头:
请求标头
OPTIONS /v1/account/login HTTP/1.1
Host: api.cake.dev
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:48.0) Gecko/20100101 Firefox/48.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://demo.angular.dev
Connection: keep-alive
响应标头
HTTP/1.1 400 Bad Request
Date: Wed, 07 Sep 2016 08:34:55 GMT
Server: Apache/2.4.17 (Win64) PHP/5.6.16
X-Powered-By: PHP/5.6.16
X-DEBUGKIT-ID: b4e5654a-cefb-43b7-bf19-4e8c7ffdb0e0
access-control-allow-origin: *
access-control-allow-methods: GET, POST, OPTIONS
access-control-allow-headers: Content-Type, Authorization, X-Requested-With, Accept
Access-Control-Allow-Credentials: true
access-control-max-age: 0
Content-Length: 147
Connection: close
Content-Type: text/html; charset=UTF-8
CakePHP 3 中是否有一种方法可以处理此 OPTIONS 请求并返回正确的响应,以便下一个 POST 请求正常工作?
请帮忙。 谢谢
【问题讨论】:
标签: php angularjs rest cors cakephp-3.0