【发布时间】:2018-10-01 13:03:07
【问题描述】:
我想在 laravel 的 dingo api 中应用 cors。 因为,我收到了这个错误。
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 500.
我已经试过了。 创建 Cors 中间件。
像这样添加 Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials',' true');
}
}
然后像这样修改Kernel.php。
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \App\Http\Middleware\Cors::class,
];
现在,我想知道如何在 dingo api 路由中添加中间件。 路线是这样的。
$api->version('v1', function($api){
$api->GET('statelist', 'App\Http\Controllers\HospitalController@statelist');
});
$api->version('v1', function($api){
$api->GET('citylist', 'App\Http\Controllers\HospitalController@citylist');
});
【问题讨论】: