Postman'POST'请求成功,但Angular 5'Post'无效

时间:2018-03-18 03:38:40

标签: angular

我正在尝试通过Web API将数据对象插入数据库。当我使用Postmen时,POST请求是成功的。但在角度5应用程序发布请求表示500内部保护程序错误。这是我的源代码。

player.service.ts

@Injectable()
export class PlayerService {


  private _postPlayer = 'http://192.168.8.101/api/Values/insertData';
  constructor(private _http: HttpClient) { }
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',

    })
  };

  // save the new player

  save(palyer: Player): Observable<Player> {

    console.log(palyer.playingRole);
    return this._http.post<Player>(this._postPlayer, palyer, this.httpOptions)
  }
}

这是我的组件

export class AddplayerComponent implements OnInit {
 player: Player = new Player(); 
 playerAdd: FormGroup;
 players: Player[];

  constructor(private plService: PlayerService) { }

  ngOnInit() {
    this.playerAdd = new FormGroup(
     {
      firstName: new FormControl(),
      lastName: new FormControl(),
      nickName: new FormControl(),
      birthday: new FormControl(),
      playingRole: new FormControl(),
      battingStyle: new FormControl(),
      bowllingStyle: new FormControl(),
      mobileNumber: new FormControl(),
      email: new FormControl() 


     }

    );


  }

  save() {
    console.log(this.playerAdd.value);
   this.player = this.playerAdd.value;
   this.plService.save(this.player)
   .subscribe();
  }

}

以下是我的ASP.NET WebApi帖子

[HttpPost]
public void insertData([FormBody] Player Ob){
  // to connect EF6 context

}

获取请求工作正常。但是Post请求不起作用。

2 个答案:

答案 0 :(得分:1)

您需要stringify您的对象:

  return this._http.post<Player>(this._postPlayer, JSON.stringify(palyer), this.httpOptions)

并将microsoft.aspnet.webapi.cors包添加到API。

答案 1 :(得分:0)

错误是我在这里没有添加到API的microsoft.aspnet.webapi.cors包。只是添加它和它的工作正常。谢谢大家的支持。