我正在使用Laravel 5.1開發RESTful API。我的終端在郵差上正常工作。但是當我將它與前端集成時,它正在跟蹤錯誤。laravel 5.1 restFull api的訪問控制源
XMLHttpRequest無法加載 http://ideahubapi.dev/api/v1/users/register。
請求的 資源上不存在「Access-Control-Allow-Origin」標頭。
原因'http://ideahubfront.dev'因此不允許 訪問。
響應的HTTP狀態碼爲500.
我試過下面的方法。 (1)創建核心中間件。
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
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', 'Content-Type, Accept, Authorization, X-Requested-With');
}
}
把它添加到kernal.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\Cors::class,
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'web' => \App\Http\Middleware\VerifyCsrfToken::class,
'cors' => \App\Http\Middleware\Cors::class,
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
}
,並routes.php文件
Route::group(['middleware' => ['web', 'core'], 'prefix' => 'api/v1'], function(){
// get single user by user id
Route::get('getuserbyid/{user_id}', '[email protected]');
Route::post('users/register', '[email protected]');
});
之後選擇請求工作。但發佈請求仍然相同。
(2)爲控制器手動添加標題。喜歡這個。
return response()->json([$user, $merchant], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Cache-Control, Connection, Date, Server, Content-Type, User-Agent, Accept, Referer, Authorization,Origin, Accept-Encoding, Content-Length, Host, Connection, X-Requested-With');
沒有運氣。夥計們,請幫助我。我爲此渴望死亡。我的客戶希望看到註冊。我堅持這一點。
中間件在'routes.php'指定應該是相同的內核。改變這個'['middleware'=> ['web','cors']' – xmhafiz
非常感謝。之前我沒有注意到。 –