使用Angular 6的PUT请求的CORS问题

时间:2018-06-11 23:15:47

标签: angular cors

在我的应用程序中,我已经成功完成了GET,POST和DELETE请求,但这是我的第一个PUT查询。 我还检查了我的API没有问题直接从邮递员查询。

所以,它似乎与Angular有关,这是我的代码:

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

export class TournamentService {
  update(tournament: Tournament, tab: string): Observable<any> {
      const tournamentUrl = this.tournamentsUrl + tournament.slug;
      console.log(tournamentUrl); // URL is OK
      return this.http.put(tournamentUrl, tournament, httpOptions).pipe(
        catchError(this.handleError<any>('updateTournamentGeneral'))
      );
    }
  }

我收到CORS错误消息:

Failed to load https://api.kz-api.test/tournaments/fake-tournoi: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
Blocked current origin from receiving cross-site document at https://api.kz-api.test/tournaments/fake-tournoi with MIME type text/html.

但就我而言,我明确要求MIME类型为application/json

以下是我在API端的Lumen中的中间件代码:

class CorsMiddleware
{
    public function handle($request, \Closure $next)
    {
        $headers = [
            'Content-type' => 'application/json;charset=UTF-8',
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age' => '86400',
            'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers')
        ];
        if ($request->isMethod('OPTIONS')) {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->headers->set($key, $value);
        }
        return $response;
    }
}

知道如何解决这个问题吗?

0 个答案:

没有答案