2017-10-28 24 views
2

我遵循this post中的說明並將以下內容應用於我的Laravel 5.4後端,這是我的Angular Web客戶端的REST API。Laravel 5.4中的Access-Control-Allow-Origin標題響應不適用於POST

首先,我安裝了一個Cors中間件

php artisan make:middleware Cors 

我去APP/HTTP /中間件/ Cors.php,並添加了兩個頭:

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

app/Http/Kernel.php添加'cors' => \App\Http\Middleware\Cors::class$routeMiddleware

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, 
]; 

,最後加入middleware('cors')到API的路由映射,如:

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

但是,只有我GET請求工作:

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

任何想法,爲什麼只有GET要求作品但不是POST


這是我如何創建在api.php文件的路徑:

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

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

響應:

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 

POST呼叫
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 

響應

如您所見,由於某些原因,標題未設置在POST響應中。

回答

0

我還以爲你需要添加此

- >標題( '訪問控制允許報頭', 'Content-Type的,授權X請求-隨着');

+0

不幸的是,這並沒有幫助。由於某些原因,POST響應中的標題完全丟失。 – displayname

+0

在api.php中使用控制器方法調用哪種方法?它是POST方法嗎? –

+0

是的,我添加了兩條路線來解決我的問題。我分別爲這些呼叫調用'Route :: get'和'Route :: post'。 – displayname