0

Hi fellow StackOverflow users.

I want to fetch the string that comes from web api (Asp.net Core)

This is the code for my controller:

        [HttpPost("Xml")]
        public string Xml()
        {
            try
            {
                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    return _xmlBeautifier.Beautify(reader.ReadToEnd());
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }

And this is my Angular Code:

onSubmit() {

    const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'text/xml',
        'Content-Type': 'text/xml'
      })
    };

    this.http.post('http://localhost:5000/api/xml/xml', this.xmlForm.controls['XmlData'].value, httpOptions)
    .subscribe(res => {
      alert('SUCCESS !!');
    })
  }

What I am doing for now is checking if the string which is XML is fetched correctly. I don't have a code yet to print the parsed XML but I already have the error.

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()

How do I fix the error? I already tested the API using Postman and it worked correctly.

Please see the screenshot below

PostMan Screenshot

Update:

Here is the full error message:

 HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/xml/xml", ok: false, …
    message: "Unexpected token < in JSON at position 0"
stack: "SyntaxError: Unexpected token < in JSON at position 0↵    at JSON.parse (<anonymous>)↵    at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19139:51)↵    at ZoneDelegate.invokeTask (http://localhost:4200/poly


    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
    message: "Http failure during parsing for http://localhost:5000/api/xml/xml"
    name: "HttpErrorResponse"
    ok: false
    status: 200
    statusText: "OK"
    url: "http://localhost:5000/api/xml/xml"

And I'm also using the paper-dashboard-angular template from creative-tim

Update:

I uploaded the sample web api and the sample angular code that i'm using

https://github.com/AngularLearner18/WebAPI

https://github.com/AngularLearner18/Angular

1 Answer 1

1

The default value of the response type for HttpClient is JSON. If you would like to request non-JSON data, you just have to set the header to the following:

this.http.get('...', { responseType: 'text' }); 
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'

In your case, it should be

  onSubmit() {
    this.http.post('http://localhost:5000/api/xml/xml', { responseType: 'text' })
      .subscribe(res => {
        alert('SUCCESS !!');
      });
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Good day. I'm still receiving the error. What i did is pasted your code for onSubmit() but the error is still there. I update the question and pasted the full error in case i missed an important detail. Thank you
I created a sample problem to try your solution, and I'm able to call the API using the code above (I edited the comment above). Otherwise, could you post your code in GitHub for me to try on my computer?
Hello Good day. I updated the question. I uploaded the web api and the angular code. And as of now i tried the solution you provided but still. It's not working yet. Thank you so much for your time and help
Just updated the solution. You just need to use an object with a responseType: text to pass to your post options. If you use HttpHeader, you will have the error.
It's working now. Thank you so much for your time. Stackoverflow member are the best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.