【发布时间】:2017-05-27 13:36:32
【问题描述】:
我是 Rest API 的新手。我正在尝试从我的应用程序中调用跨域休息 API。 这是我的代码-
$.ajax({
type: "GET",
async: false,
url: 'http://xx.xxx.xxx.xx:9003/GetProjectList',
contentType: "application/json",
dataType: "json",
traditional: true,
CrossDomain: true,
data: {
StartDate: '2016-12-20',
EndDate: '2017-01-10'
},
success: function (data) {
alert("Success");
alert(data);
},
error: function (xhr, textStatus, errorThrown) {
alert("Failed");
alert(xhr);
alert(textStatus);
alert(errorThrown);
}
});
但我得到的错误是
OPTIONS http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10 405 (Method Not Allowed)
XMLHttpRequest cannot load http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64207' is therefore not allowed access. The response had HTTP status code 405.
我在这里有什么遗漏吗?任何代码或配置?
如果我直接从浏览器或 Postman 中点击该 URL,它的工作正常。但它在应用程序中不起作用。
【问题讨论】:
-
这是基本的 CORS 错误。您应该在响应标头中设置所需的 CORS 标头。有很多可用的答案。顺便问一下,您的服务是 web-api 还是 wcf-rest?你不应该同时添加两个标签
-
您只需要允许 CORS。知道这一点,它并不总是有效!
-
为什么要在 GET 请求中设置 Content-Type?
标签: ajax rest model-view-controller asp.net-web-api wcf-rest