Access-Control-Allow-Origin header response in Lar

2019-07-14 00:19发布

问题:

I followed the instructions from this post and applied the following to my Laravel 5.4 backend which is a REST API for my Angular web client.

First I installed the Cors middleware

php artisan make:middleware Cors

I went to app/Http/Middleware/Cors.php and added the two headers:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}

I added 'cors' => \App\Http\Middleware\Cors::class to $routeMiddleware in app/Http/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,
];

and finally added middleware('cors') to the api routes mapping as such:

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->middleware('cors')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

However, only my GET request is working:

onSubmit() {
  // Fails: "No 'Access-Control-Allow-Origin' header is present.."
  console.log('Submit ..');
  this.http.post('http://localhost:8080/api/register', JSON.stringify(this.registerForm.value))
    .subscribe(
        data => alert('yay'),
        err => alert(err.error.message)
    );
}

onCancel() {
  // Is working..
  console.log('Cancel ..');
  this.http.get('http://localhost:8080/api/helloworld')
    .subscribe(
      data => alert(data),
      err => alert('error')
    );
}

Any idea why only the GET request works but not the POST?


This is how I create the routes in the api.php file:

Route::get('/helloworld', function (Request $request) {
    return ['Hello World!'];
});

Route::post('/register', function (Request $request) {
    // dd($request->input("email"));
    return ['register'];
});

Response for the GET call:

Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-cache, private
Connection:close
Content-Type:application/json
Date:Sat, 28 Oct 2017 15:14:27 GMT
Host:localhost:8080
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1

Response for the POST call:

Allow:POST
Cache-Control:no-cache, private
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sat, 28 Oct 2017 15:10:30 GMT
Host:localhost:8080
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1

as you can see, for some reason the headers are not set in the POST response.

回答1:

I thinking also you need to add this

->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');