Clock
Clock

Reputation: 984

Error when reading the WEB API response in a html page

I have a self hosting WEB API which seems to work fine. Below is its short implementaion:

class Program
{
    static void Main(string[] args)
    {
        string baseAddress = "http://localhost:9000/";

        // Start OWIN host 
        using (Microsoft.Owin.Hosting.WebApp.Start<Startup>(url: baseAddress))
        {
            Console.ReadLine();
        }
    }
}

class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }
}

public class Product
{
    public string Name { get; set; }
}

public class ValuesController : ApiController
{
    Product myPro = new Product { Name = "Test 123" };

    // GET api/values 
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5 
    public IHttpActionResult Get(int id)
    {
        return Ok(myPro);
    }

    // POST api/values 
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5 
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5 
    public void Delete(int id)
    {
    }
}

When I access the "http://localhost:9000/" address in a web browser and give the right routing parameters I get the expected results.

Then I added the following web page:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2/jquery.min.js"></script>

    <script>
        var uri = 'http://localhost:9000/api/values';

        function formatItem(item) {
            return item.Name;
        }

        function find() {
            var id = $('#prodId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#product').text(data.Name);
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }
    </script>
</head>
<body>
    <div>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
    </div>
</body>
</html>

I hosted then this page on my local IIS server to an address like "http://localhost:9998/".

I start the self hosted WEB API then I click the "Search" button from the web page, the Get action gets called, but instead of seeing the "Test 123" result in my web page I get all the time the "Error" message without any other details.

Is something wrong to the web page, the way how the jquery is trying to fetch the data, or is there something that needs to be configured ?

Please note that this is all my code and no other configurations were done.

Upvotes: 0

Views: 101

Answers (1)

Christian Kuetbach
Christian Kuetbach

Reputation: 16060

Different ports means different origin. You can't access the api from the webserver.

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

You would need a reverse proxy or host api and website from your application ore cors header.

The IIS has a reverse proxy module: https://weblogs.asp.net/owscott/creating-a-reverse-proxy-with-url-rewrite-for-iis

Upvotes: 1

Related Questions