在 html 页面中读取 WEB API 响应时出错



我有一个自托管WEB API,它似乎工作正常。以下是它的简短实现:

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)
    {
    }
}

当我在 Web 浏览器中访问"http://localhost:9000/"地址并提供正确的路由参数时,我得到了预期的结果。

然后我添加了以下网页:

<!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>

然后,我在本地 IIS 服务器上将此页面托管到类似"http://localhost:9998/"的地址。

我启动自托管的WEB API,然后单击网页上的"搜索"按钮,调用Get操作,但不是在我的网页中看到"Test 123"结果,而是一直收到"错误"消息,没有任何其他详细信息。

网页是否有问题,jquery尝试获取数据的方式,还是需要配置某些内容?

请注意,这是我的所有代码,没有进行其他配置。

不同的端口意味着不同的来源。您无法从网络服务器访问 API。

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

您需要从应用程序或 cors 标头中获取反向代理或主机 api 和网站。

IIS 有一个反向代理模块:https://weblogs.asp.net/owscott/creating-a-reverse-proxy-with-url-rewrite-for-iis

最新更新