尝试访问 Web API 时 GET 不起作用

问题描述 投票:0回答:3

我在 .net 中编写了一个简单的 Web API,并在 Windows 10 上的 IIS 下创建的网站上运行它。如果我将 URL 输入 Chrome“https://localhost:64591/api/custom”,则 JSON 会传递从数据库中调用的记录。没问题。

我将相同的 URL 放入

XMLHttpRequest
对象中,并且
onload
事件永远不会发生。作为测试,我用我知道有效的外部 URL 替换了该 URL。
onload
事件触发并且响应对象起作用。 IIS 似乎发生了一些问题,它阻止了“get”请求。

下面是代码。这是有效的外部 URL:https://ghibliapi.herokuapp.com/films ..... 通过 IIS 访问 API 肯定有问题。

var request = new XMLHttpRequest();
request.open('GET', 'https://localhost:64591/api/custom', true)
request.onload = function () 
{
  alert(this.response); 
}
request.send();
.net iis xmlhttprequest webapi
3个回答
0
投票

试试这个,对我有用(我使用Python服务器,如果你也想看到它评论)

url="127.0.0.1"; // or your loaclhost etc
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var response = xhttp.responseText;
    }
};
xhttp.open("GET", url, true);
xhttp.send();

0
投票

您很可能遇到 CORS 问题。

尝试让服务器将

Access-Control-Allow-Origin: *
作为标头的一部分发送回来。

我对 IIS 几乎一无所知,但是 这个 可能会有所帮助。


-1
投票

看起来这是一个 CORS 问题。我可以从 html 页面执行 GET 和 POST,只要该页面与我的 Web api 来自同一服务器,并且我没有在字符串“api/custom”中提及服务器,而不是“https://localhost” :64591/api/自定义'。我对此很满意,因为我只是在练习 Web api 的东西。但有时我必须学习如何在 iis 中配置 CORS 模块。

© www.soinside.com 2019 - 2024. All rights reserved.