I have developed a Web API in asp.net 5 where I am fetching a list of books available in the database and returning it as JSON
. The API is running at Port number 5000
(http://localhost:5000/api/bookstore
)
Now I have a website set up on my PC with a single index.html
file where I am trying to consuming the above API endpoint. The website is running at a different port (52786
).
Initially with dataType: 'json'
I was getting the following console error:
XMLHttpRequest cannot load http://localhost:5000/api/bookstore. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52786' is therefore not allowed access.
To avoid above 'Access-Control-Allow-Origin'
error I used dataType: 'jsonp'
, (as suggested by Gavin here). Using jsonp
apparently removes the error from console but nothing is showing up when I am running the page. How would I know whether the endpoint is at all being hit and if it is why the data is not being pulled?
But when I am running http://localhost:5000/api/bookstore
separately on the browser it is giving me data perfectly.
Below is the code snippet I used to invoke API endpoint using jQuery and ajax:
<script type="text/javascript">
$(document).ready(function () {
//jQuery.support.cors = true;
$.ajax({
type: "GET",
url: "http://localhost:5000/api/bookstore",
dataType: 'jsonp',
success: function (data) {
alert(data);
$("#response").html(data);
},
error: function (err) {
}
});
});
</script>
NB: Both the website and the Web API port are running.
UPDATE (Screenshots)
Image 1: Console messages when invoking the endpoint from another website (as could be seen I am running Chrome with disable-web-security
in order to bypass CORS. I was successful in the past by doing this in dev environment so tried here as well.