我正在尝试将 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
);
}
}
@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 });
}
}
您应该在后端仅返回文本或仅返回 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'
}),
};