【问题标题】:Ionic 3 - Laravel - Not sending back to the client the headers that allow CORSIonic 3 - Laravel - 不向客户端发送允许 CORS 的标头
【发布时间】:2018-11-04 22:44:22
【问题描述】:

我有一个使用 Ionic 3 开发响应式 Web 应用程序的系统,以及作为 Rest API 的 Laravel。在本地服务器上它工作得很好,但是当我去部署应用程序时它出现了 CORS 错误。

我已经在 ionic.config.json 中定义了代理 [{"path", "proxyUrl"}]。为了将系统投入生产,我还需要进行任何其他更改吗?

我在 Apache 服务器上运行。

登录请求:

login() {
this.http.post<any>('http://www.example.com/api/login', this.user)
  .subscribe(data => {...})};

我的 Http 拦截器:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let authRequest = req;
  const token = this.session.tokenGetter();
  if (token) {
    authRequest = req.clone({
      setHeaders: {
        'Access-Control-Allow-Origin': '*',
        'Authorization': `Bearer ${token}`
      }
    })
  }
  return next.handle(authRequest);
}

Laravel 中的路线:

Route::post('login', function (Request $request) {
  $data = $request->only('email', 'password');
  $token = \Auth::guard('api')->attempt($data);
  if (!$token) {
    return response()->json([
      'error' => 'Credentials invalid'
    ], 400);
  }
  return ['token' => $token];
});

Laravel 中的 CORS:

<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
    public function handle($request, Closure $next)
    {
        if($request->is('api/*')){ //api/products /api/login
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: Content-Type, Authorization');
        }
        return $next($request);
    }
}

【问题讨论】:

  • 您尝试发送 POST 请求的 API 端点需要配置为也处理 OPTIONS 请求——它需要发送 Access-Control-Allow-Origin 标头以响应 OPTIONS 请求,并且需要使用 200 OK 成功消息来响应 OPTIONS 请求。如果它不做这两件事,那么浏览器将不允许您的前端 JavaScript 代码访问来自该 API 的响应。

标签: laravel ionic-framework cors web-deployment


【解决方案1】:

这意味着您的服务器没有将允许 CORS 的标头发送回客户端:

1.Access-Control-Allow-Origin 2.Access-Control-Allow-Methods

创建新的中间件:

php artisan make:middleware Cors

Cors.php

<?php // /app/Http/Middleware/Cors.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');
    }
}

Kernel.php

<?php // /app/Http/Kernel.php
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'cors' => \App\Http\Middleware\Cors::class, // <<< add this line
];

routes.php

<?php
Route::get('', ['middleware' => 'cors', function() {
    return 'You did it!';
}]);

【讨论】:

  • 在我的本地机器上工作,但服务器没有工作
  • 我尝试了几种我在互联网上找到的解决方案,但都没有解决问题,我在“Allow-Control-Allow-Origin: *”中安装了一个谷歌扩展来忽略这个错误,因此它返回一个 404 错误。
猜你喜欢
  • 2018-02-07
  • 2017-11-11
  • 2022-06-24
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
相关资源
最近更新 更多