嘿,我有这个 Web 服务,我正在尝试将一些 JSON 发送到:
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
url: serviceURL + 'theQ',
headers: {
'Access-Control-Allow-Origin' : '*',
},
data: JSON.stringify({ query: sqlCC, empImg: false }),
success: function (data) {
var obj = jQuery.parseJSON(data);
app.employeeData = obj[0];
},
error: function (xhr, status, error) {
console.log('checker1' + xhr.responseText);
}
});
然后我在我的 web api 2 函数上安装了 CORS:
[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Route("theQ")]
public IHttpActionResult theQ(theQ.theQVars data)
{
.... code here.....
}
但是当我尝试执行该 AJAX 时,我在 CHROME 中得到以下信息:
XMLHttpRequest cannot load http://dev-zzzz/xxxx/Q/SELECT%20DI----D%20ASC/false?_=1454534694738. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://tst-zzzz.com' is therefore not allowed access.
现在,如果我指定 * 允许任何,为什么我会收到此错误?
最佳答案
我认为你弄错了 CORS。
Access-Control-Allow-Origin header 应该出现在远程站点上的 HTTP 请求的响应中,而不是在请求中。
在某些情况下,浏览器还会发出预检请求 - 使用 OPTIONS 方法。
预检请求的响应应包含
各种访问控制 header
阅读更多信息 here
但是您的服务器应该根据您的设置添加此 header
[EnableCors(origins: "*", headers: "*", methods: "*")]
您是否正确启用了 CORS 支持?
尝试按照记录在您的 HttpConfiguration 上调用 enableCors() here
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
关于javascript - web api 2 CORS 不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35188121/