HttpErrorResponse when calling .net core method from Angular 8

前提是你 提交于 2020-04-16 03:52:01

问题


I'm calling a controller method and returning success if the operation is complete.But i keep getting the following error

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/File/create", ok: false, …}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}status: 200statusText: "OK"url: "http://localhost:5000/api/File/create"ok: falsename: "HttpErrorResponse"message: "Http failure during parsing for http://localhost:5000/api/File/create"error: {error: SyntaxError: Unexpected token s in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHtt…, text: "success"}__proto__: HttpResponseBase

[HttpPost("create")]
        public ActionResult<File> Create([FromBody]File file)
        {
            _fileService.Create(file);

            return Ok("success");
        }

回答1:


There is an opened issue and you have many solutions: https://github.com/angular/angular/issues/18396

The best way is to change the responseType:

this.http.get(url, {responseType: 'text'})

This is the reference: https://angular.io/guide/http#requesting-non-json-data




回答2:


The Angular side expects a JSON, the called action method in your example returns a plain text string. For example returning this way the client side will get a JSON and it will be able to parse it:

[HttpPost("create")]
public ActionResult<string> Create([FromBody]File file)
{
    _fileService.Create(file);
    return Ok(new { str="success" });
}


来源:https://stackoverflow.com/questions/61168850/httperrorresponse-when-calling-net-core-method-from-angular-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!