angular - 带有 Angular 6 的 PUT 请求的 CORS 问题

标签 angular cors

在我的应用程序中,我已经成功地发出了 GET、POST 和 DELETE 请求,但这是我的第一个 PUT 查询。
我还检查了我的 API 直接从 postman 那里查询没有问题。
所以,它似乎与 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;
    }
}
知道如何解决这个问题吗?

最佳答案

对我来说,我不得不在请求的最后更改我的 http 请求,不要使用“/”,这个问题仅适用于 PUT

return $http.put(config.apiUrl + '/cit/product/', product);
对此
return $http.put(config.apiUrl + '/cit/product', product);

关于angular - 带有 Angular 6 的 PUT 请求的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50807275/

相关文章:

javascript - YouTube 资源上 window.fetch 的 CORS 错误

javascript - 如何添加跨域资源共享请求头?

spring - 浏览器未连接到 Springboot Websocket (sockjs)

node.js - 在expressjs中提供应用程序时,Angular应用程序导航不适用

Angular 7 : refreshing page with query parameters causing path mismatch

unit-testing - Angular 2 单元测试可观察到的错误 (HTTP)

angularjs - Angular 问题和 "No ' Access-Control-Allow-Origin' header ”- 使用 OAuth 2、Passport、Express 和 Node

javascript - 如何在 rxjs 中做链式序列

javascript - 根据服务响应动态显示/隐藏输入框

python - 如何在python中多线程调用另一个端点方法?