laravel 5.1 access-control-origin for restFull api

时间:2016-12-02 04:01:20

标签: php laravel laravel-5.1

我正在使用Laravel 5.1开发RESTful API。我的端点在Postman上正常工作。但是当我将它与前端集成时,就会出现错误。

  

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}', 'UserController@getSingleUserById');

    Route::post('users/register', 'UserController@register');

});

之后选项请求有效。但是帖子请求仍然相同。

(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');

没有运气。伙计们请帮帮我。我为此而死。我的客户希望看到注册。我坚持这个。

2 个答案:

答案 0 :(得分:1)

Change

Route::group(['middleware' => ['web', 'core']

to

Route::group(['middleware' => ['web', 'cors']

It doesn't work since it doesn't match up with the one in the kernel.

答案 1 :(得分:0)

CORS是你的诅咒的名称,这是一个解决方案:https://github.com/barryvdh/laravel-cors