2017-10-28 23 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