0

Cannot catch error using jQuery... Any clue?

JS

var url = "http://localhost:57371/api/Apps/";

$.ajax({
    url: url,
    type: "get",    
    success: function (response) {
        alert("second success");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(XMLHttpRequest.responseText);
    }
});

ASP.NET WEBAPI 2

[Authorize]
    public class AppsController : ApiController
    {
        [Route("api/Apps/")]
        public IEnumerable<App> Get()
        {
            var r = new List<App>();

            using (var ctx = new REDEntities())
            {
                if (ctx.Apps.Any())
                    r.AddRange(ctx.Apps.ToList());
            }

            return r.ToList();
        }
}

Console

jquery-3.1.1.js:9536 GET http://localhost:57371/api/Apps/ 401 (Unauthorized) send @ jquery-3.1.1.js:9536 ajax @ jquery-3.1.1.js:9143 (anonymous) @ Index:96 dispatch @ jquery-3.1.1.js:5201 elemData.handle @ jquery-3.1.1.js:5009 Index:1 XMLHttpRequest cannot load http://localhost:57371/api/Apps/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:57166' is therefore not allowed access. The response had HTTP status code 401.

enter image description here

Samir
  • 1,312
  • 1
  • 10
  • 16
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 1
    You'll need to enable `CORS` on web api , because you are trying to access the api from a different website. – Mat J Jan 10 '17 at 12:37
  • @MathewJibin Please tell me how to do it. – NoWar Jan 10 '17 at 12:39
  • 1
    Its rather simple,[See this guide](https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api) for details. Essentially it boils down to calling `config.EnableCors()` after installing `Microsoft.AspNet.WebApi.Cors` package. – Mat J Jan 10 '17 at 12:41
  • the question is about catching the error instead, isn't it? – Amit Kumar Ghosh Jan 10 '17 at 12:43
  • @AmitKumarGhosh Yes, I need to display `alert(XMLHttpRequest.responseText);` the error properly and that's it. – NoWar Jan 10 '17 at 12:45
  • 1
    @Dimi, [you cannot access](http://stackoverflow.com/questions/4844643/is-it-possible-to-trap-cors-errors) responseText of a request which result in CORS error. – Mat J Jan 11 '17 at 05:22

0 Answers0