POST 请求时出现 Angular 前端 CORS 错误

问题描述 投票:0回答:1

Here is the Browser-Console Error Message and Network Analyzing 当我尝试 POST 到 JAVA-SPRING 后端时,出现 CORS 错误。但是来自 http://localhost:8080/api/currentPlayer 的 GET 请求正在工作..

此外,我还在 POST 请求中添加了“Access-Control-Allow-Origin Header”:“*”。我仍然收到错误,但缺少此标头。这很令人困惑...

这是我发出请求的服务的角度代码:

import { Injectable } from '@angular/core';
import { Player } from './Player';
import { Observable, catchError, map, of } from 'rxjs';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { PlayerPost } from './PlayerPost';

@Injectable({
  providedIn: 'root'
})
export class PlayerService {

  constructor(private http: HttpClient,) { }

  private playerUrl = 'http://localhost:8080/api/currentPlayer';

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Access-Control-Allow-Origin': '*'
    })
  };
  
  playerList: Player[] = [
    {
      "id" : 0,
      "name" : "Thorsten",
      "stack" : 5000
    },
    {
      "id" : 1,
      "name" : "Marietta",
      "stack" : 5000
    },
    {
      "id" : 2,
      "name" : "Rüdiger",
      "stack" : 5000
    },
    {
      "id" : 3,
      "name" : "Hans",
      "stack" : 5000
    }
  ]

  index: number = 0;

getPlayersObservable(): Observable<Player[]> {
    return this.http.get<Player[]>(this.playerUrl);
}

getPlayerList(): Player[] {
  this.getPlayersObservable().subscribe((x:Player[]) => {this.playerList = x;});
  return this.playerList;
}

postPlayer(player: PlayerPost) {this.http.post<any>(this.playerUrl, player, this.httpOptions).subscribe((res)=> console.log(res));

}

}

我尝试使用“http://localhost:8080/api/currentPlayer”声明 Access-Control-Allow-Origin 标头。

我在服务器响应上添加了 Access-Control-Allow-Origin 标头。

angular http servlets cors xmlhttprequest
1个回答
0
投票

必须在服务器端启用 CORS 才能使您的请求成功

© www.soinside.com 2019 - 2024. All rights reserved.