我在使用Lumen通过Swagger UI创建的API时遇到了CORS错误。所以我创建了一个中间件来解决这个CORS问题:
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
在我的路由中使用这个中间件用于该API,现在使用此我的corse错误问题已解决,但API无法正常工作,为以下代码抛出错误:
//**** code that throwing error starts ****
$config = app()->make('config');
$data = array_merge([
'client_id' => $config->get('secrets.client_id'),
'client_secret' => $config->get('secrets.client_secret'),
'grant_type' => $grantType,
'username' =>$data['username'],
'password' =>$data['password']
], $data);
$http = new Client();
$headers = ['Content-Type' => 'application/json'];
$guzzleResponse = $http->post( $config->get('app.url').'/oauth/token', [
'form_params' => $data,
]);
$tokenDetails = json_decode($guzzleResponse->getBody(),true);
//************** Code throwing error ends ******
现在当我从路由中删除中间件时,API正在与POSTMAN一起使用,但是为SWagger抛出了CORS错误,当我使用中间件解决CORS问题时,API无法正常工作。
答案 0 :(得分:0)
在.htaccess
中添加此行RewriteCond%{REQUEST_METHOD}选项 RewriteRule ^(。*)$ $ 1 [R = 200,L] 在RewriteEngine On line
之后