繁体   English   中英

Angular:我不断收到错误 400:使用 httpPost 时出现错误请求“发生一个或多个验证错误”

[英]Angular: I keep on getting error 400: bad request "One or more validation error occured" when using httpPost

服务.ts

  addTankValues(data:any) {
return this.http.post(this.TankApiUrl + "...", data).pipe(
  tap(()=>{
    this.RefreshRequired.next();
  })
);

}

订阅 httpPost:

 SaveTV(){
if(this.TVForm.valid){
  console.log(this.TVForm.value);
  this.service.addTankValues(this.TVForm.value).subscribe(result=>{
    this.TVFormresp=result;
    console.log(this.TVFormresp);
    this.alert = true;
    this.TVForm.reset();
  });
}else{
  console.log("form not valid");
}

我不断收到 400 错误:向我的 asp.net 后端发送发布请求时出现错误请求。 “发生一个或多个验证错误。

  1. 配置您的 http 标头选项
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    Authorization: 'my-auth-token'
  })
};
  1. 应用程序通常在提交表单时使用 POST 请求将数据发送到服务器。 在以下示例中,HeroesService 在将英雄添加到数据库时发出 HTTP POST 请求。 app/heroes/heroes.service.ts (addHero)
    
/** POST: add a new hero to the database */
addHero(hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

HttpClient.post() 方法与 get() 类似,因为它有一个类型参数,您可以使用它来指定您希望服务器返回给定类型的数据。 该方法接受一个资源 URL 和两个附加参数:

取自https://angular.io/guide/http

使用 cors 修复此问题

从“@angular/common/http”导入 { HttpHeaders };

const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', Authorization: 'my-auth-token' }) };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM