在我的应用程序中,我已经成功地发出了 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/