【问题标题】:"Http failure during parsing" in AngularAngular中的“解析期间的Http失败”
【发布时间】:2021-02-22 14:35:40
【问题描述】:

我正在尝试将 Angular 中的前端连接到使用 .NetCore 开发的 Api,但出现以下错误

Http failure during parsing for http://localhost:5000/User/register

尽管出现错误,用户仍被保存到数据库中。 下面是我的休息服务,我的组件ts和后端的注册方法

休息服务

const endpoint = 'http://localhost:5000/';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
};

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

  constructor(private http: HttpClient) { }

  private extractData(res: Response) {
    let body = res;
    return body || {};
  }

  addUser(user: User): Observable<User> {
    return this.http.post<User>(
      endpoint + 'User/register',
      JSON.stringify(user),
      httpOptions
    );
  }
}

注册组件.ts

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  @Input() userData: User = new User();

  constructor(  public rest: RestService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit(): void {
  }

  addUser() {
    this.rest.addUser(this.userData).subscribe(
      (result:any) => {
        console.log(result);
        this.router.navigate(['/login']);
      },
      (err) => {
        console.log(err);
        console.log("DADOS"+JSON.stringify(this.userData));
      }
    );
  }
}

后端方法

 [AllowAnonymous]
        [HttpPost("register")]
        public IActionResult Register([FromBody]RegisterModel model)
        {
            var user = _mapper.Map<User>(model);

            try
            {
                // create user
                _userService.Create(user, model.Password);
                return Ok("Successful registration");
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

【问题讨论】:

    标签: .net angular rest asp.net-core .net-core


    【解决方案1】:

    您应该在后端仅返回文本或仅返回 json。在 Ok("Successful registration") 上返回文本时,它在 BadRequest(new { message = ex.Message }) 上返回 JSON 模型。

    应该是这样的:

        [AllowAnonymous]
        [HttpPost("register")]
        public IActionResult Register([FromBody]RegisterModel model)
        {
            var user = _mapper.Map<User>(model);
    
            try
            {
                // create user
                _userService.Create(user, model.Password);
                return Ok("Successful registration");
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return BadRequest(ex.Message);
            }
        }
    

    然后,您应该在 httpOptions 中发送 responseType 参数。

      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'responseType': 'text'
        }),
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-06
      • 2019-05-13
      • 1970-01-01
      • 2020-06-03
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多