user1238784
user1238784

Reputation: 2440

Angular fails to parse string from api call (web core 3)

Controller code:

 [Route("api/[controller]")]
[ApiController]
public class AjaxController : ControllerBase
{
    ApplicationDbContext dbContext = null;
    public AjaxController(ApplicationDbContext ctx)
    {
        dbContext = ctx;
    }

    [HttpGet]
    [Route("GetString")]
    public string GetString()
    {
        return "Hello World";
    }

    [HttpGet]
    [Route("GetCategories")]
    public Category[] GetCategories()
    {
        return dbContext.Categories.ToArray();
    }
}

Angular code:

http.get<string>(baseUrl + 'api/ajax/GetString').subscribe(result => {
      console.log(result);
    }, error => console.error(error));

While Angular can parse without error the GetCategories endpoint, it cannot parse the much simpler GetString. Why? The error in the console is:

error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data" ​​text: "Hello World"

I tried wit Postman and the response is just fine, see screenshot: screenshot of Postman

Upvotes: 0

Views: 895

Answers (1)

Ash
Ash

Reputation: 11472

The issue is your response from GetString is returning just a string of value Hello World as shown by the screenshot from Postman. The GetCategories endpoint must be returning valid JSON if you are getting a valid response.

By default Angular assumes the response type of a HttpRequest to be of type json.

To fix this, specify as the second parameter to http.get() the responseType expected from the server which in your case for the GetString endpoint will be 'text'. So your http.get() call should look like the following:

http.get<string>(baseUrl + 'api/ajax/GetString', { responseType: 'text' }).subscribe(result => {
    console.log(result);
  }, error => console.error(error));

If your intention was to return valid JSON from GetString then you need to format the response from your server as appropriate.

See the Angular documentation on HttpRequest - responseType. I've included a copy below.

responseType: 'arraybuffer' | 'blob' | 'json' | 'text'

The expected response type of the server.

This is used to parse the response appropriately before returning it to the requestee.

Upvotes: 2

Related Questions