techno
techno

Reputation: 6500

Checking if response is 200 from HTTP POST request

HttpErrorResponse is 200, but the 'sucess' message never prints. Instead this shows up in the console:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/File/create", ok: false, …}
this.http.post('api/File/create', waldo, { observe: 'response' }).subscribe(data => {
    if (data.status == 200) {
        console.log("success");
    }
});

Update: enter image description here

Update2:

 [HttpPost("create")]
        public ActionResult<File> Create([FromBody]File file)
        {
            try
            {
                _fileService.Create(file);
                return Ok("sucess");
            }
            catch(Exception e)
            {
                return NotFound();
            }



        }

Upvotes: 1

Views: 1840

Answers (2)

Milan Tenk
Milan Tenk

Reputation: 2695

The Angular side expects by default a JSON response. The endpoint does not respond a JSON object, it responds a plain text. The Angular side tries to parse the plain text as JSON but it is not able to do it, this is why an error is thrown.

There are 2 ways to handle this issue:

On server side a JSON has to be returned as answered here.

Or the http client on Angular side should be configured to expect plain text.

Upvotes: 1

David
David

Reputation: 34435

I think it's because your create API does not return json.

Try specifying responseType in the request options so that angular does not try to parse the response content as a json object:

this.http.post('api/File/create', waldo, { observe: 'response', responseType: 'text' })

Upvotes: 3

Related Questions