Skip to content

Commit 1a4cd41

Browse files
committed
fix APIAuto请求跨域问题
1 parent 8bffc24 commit 1a4cd41

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

app/Middleware/CorsMiddleware.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
4+
declare(strict_types=1);
5+
/**
6+
* @author kvnZero
7+
* @contact kvnZero@github.com
8+
* @time 2021/11/20 11:16 上午
9+
*/
10+
11+
namespace App\Middleware;
12+
13+
use Hyperf\Utils\Context;
14+
use Psr\Http\Message\ResponseInterface;
15+
use Psr\Http\Message\ServerRequestInterface;
16+
use Psr\Http\Server\RequestHandlerInterface;
17+
18+
class CorsMiddleware
19+
{
20+
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
21+
{
22+
$response = Context::get(ResponseInterface::class);
23+
$response = $response->withHeader('Access-Control-Allow-Origin', $request->getHeaders()['origin'])
24+
->withHeader('Access-Control-Allow-Credentials', 'true')
25+
->withHeader('Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization');
26+
27+
Context::set(ResponseInterface::class, $response);
28+
29+
if ($request->getMethod() == 'OPTIONS') {
30+
return $response;
31+
}
32+
33+
return $handler->handle($request);
34+
}
35+
}

config/autoload/middlewares.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
*/
1212
return [
1313
'http' => [
14+
\App\Middleware\CorsMiddleware::class,
1415
\App\Middleware\ResponseMiddleware::class
1516
],
1617
];

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy