【问题标题】:Postman 'POST' request sucess but Angular 5 'Post' not working邮递员'POST'请求成功但Angular 5'Post'不起作用
【发布时间】:2018-11-20 12:18:25
【问题描述】:

我正在尝试通过 Web API 将数据对象插入数据库。当我使用 Postmen 时,POST 请求是成功的。但在 Angular 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

}

获取请求工作正常。但发布请求不起作用。

【问题讨论】:

  • 这意味着你的API有问题,如果有错误抛出,请查看
  • 那么,为什么邮递员 POST 工作?
  • 这意味着您从 angular 发送的数据无效
  • 能否分享一下服务器端的错误?

标签: angular


【解决方案1】:

你需要stringify你的对象:

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

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

【讨论】:

  • 哦,真奇怪!如果您在 API 上获取对象,您可以尝试调试吗
  • 谢谢大家。我防止错误。它是我的 API。对不起。
  • 再次感谢您。我也错过了这部分。
【解决方案2】:

我在这里遇到的错误是没有将 microsoft.aspnet.webapi.cors 包添加到 API。刚刚添加它并且它工作正常。谢谢大家对我的支持。

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 2019-09-22
    • 2017-12-30
    • 2021-09-14
    • 1970-01-01
    • 2020-11-23
    • 2022-06-16
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多