AccessControlCors.php 930 B

1234567891011121314151617181920212223242526
  1. <?php
  2. namespace app\middleware;
  3. use Webman\MiddlewareInterface;
  4. use Webman\Http\Response;
  5. use Webman\Http\Request;
  6. class AccessControlCors implements MiddlewareInterface
  7. {
  8. public function process(Request $request, callable $handler): Response
  9. {
  10. // 如果是options请求则返回一个空响应,否则继续向洋葱芯穿越,并得到一个响应
  11. $response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
  12. // 给响应添加跨域相关的http头
  13. $response->withHeaders([
  14. 'Access-Control-Allow-Credentials' => 'true',
  15. 'Access-Control-Allow-Origin' => $request->header('origin', '*'),
  16. 'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
  17. 'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
  18. ]);
  19. return $response;
  20. }
  21. }