Laravel 5.4中的Access-Control-Allow-Origin标头响应不适用于POST

时间:2017-10-28 14:54:19

标签: angular laravel http

我按照this post中的说明操作,并将以下内容应用到我的Laravel 5.4后端,后端是我的Angular Web客户端的REST API。

首先我安装了Cors中间件

php artisan make:middleware Cors

我去了app / Http / Middleware / 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');
}

我在'cors' => \App\Http\Middleware\Cors::class中向$routeMiddleware添加了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,
];

最后将middleware('cors')添加到a​​pi路由映射中:

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文件中创建路线的方式:

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

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

GET来电的响应:

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来电的响应:

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响应中设置。

2 个答案:

答案 0 :(得分:0)

我想你也需要添加这个

- >标题(' Access-Control-Allow-Headers','内容类型,授权,X-Requested-With');

答案 1 :(得分:0)

通常在使用laravel时,该错误并不意味着来自发布请求,也不是来自您的CORS.php或KERNEL。这可能意味着很多事情,甚至数据库列都不存在,并且由于请求来自另一台服务器,laravel试图在chrome中隐藏特定错误,并抛出该错误。要知道具体的错误并进行调试,您应该使用邮递员来触发该路由并发送该请求,邮递员会为您提供正确的错误消息。 还要用

代替您的cors.php
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, X-Auth-Token');
$response->headers->set('Access-Control-Allow-Credentials',' true');
return $response;