Angular 中的“解析期间 HTTP 失败”

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

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

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

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

休息服务

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个回答
0
投票

您应该在后端仅返回文本或仅返回 json。虽然在 Ok("成功注册") 上返回文本,但在 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'
    }),
  };
© www.soinside.com 2019 - 2024. All rights reserved.