简体   繁体   English

为什么添加额外的标头会使 AJAX 调用失败

[英]Why is adding an extra header making the AJAX call fail

AJAX call: AJAX 调用:

$.ajax({
    url: "http://myserver2:296/api/Demo/HelloWorld",
    type: "GET",
    dataType: 'JSONP',
    jsonp: "callback",
    headers: { 'API_KEY': 'mykey09090' },
    success: function (result) {
        console.log(result);
    },
    error: ajaxFailed
});

function ajaxFailed(xmlRequest) {
    alert(xmlRequest.status + ' \n\r ' +
          xmlRequest.statusText + '\n\r' +
          xmlRequest.responseText);
}

I get the following error: Failed to load resource: the server responded with a status of 403 (Forbidden) .我收到以下错误: Failed to load resource: the server responded with a status of 403 (Forbidden) However when I use Postman, I just have to add the headers with the http://myserver2:296/api/Demo/HelloWorld url it returns the string.但是,当我使用 Postman 时,我只需要添加带有http://myserver2:296/api/Demo/HelloWorld url 的标头,它会返回字符串。

Can I please get some assistance to resolve the issue.我能否得到一些帮助来解决这个问题。

My goal, is to allow the origin server along with the API key correctly provided to get the data back from the Web Api.我的目标是允许源服务器以及正确提供的 API 密钥从 Web Api 取回数据。

Adding the API_KEY header to the request triggers your browser to first send a CORS preflight OPTIONS request .API_KEY标头添加到请求会触发您的浏览器首先发送 CORS 预检选项请求 Any headers you add to a request other than headers defined as CORS-safelisted request-headers will trigger your browser to send a CORS preflight OPTIONS request.除了定义为CORS 安全列表请求标头的标头之外,您添加到请求中的任何都将触发您的浏览器发送 CORS 预检选项请求。

I can't tell for sure but it seems like the 403 you're seeing is from your server responding to that OPTIONS request, and saying it doesn't expect to get OPTIONS requests and doesn't allow them.我不能肯定,但您看到的 403 似乎来自您的服务器响应该 OPTIONS 请求,并说它不希望获得 OPTIONS 请求并且不允许它们。

The reason you don't get this from Postman is that unlike browser engines, Postman does not implement CORS, so it does not send the OPTIONS request.你没有从 Postman 得到这个的原因是与浏览器引擎不同,Postman 没有实现 CORS,所以它不会发送 OPTIONS 请求。 (Postman does not operate under the same-origin Web-security model that browsers enforce for Web applications.) (Postman 不在浏览器为 Web 应用程序强制执行的同源 Web 安全模型下运行。)

So to make your client app work as expected for scripted cross-origin access to that server, you must configure the server to respond in the right way to that CORS preflight OPTIONS request.因此,为了使您的客户端应用程序按预期工作,以便对该服务器进行脚本化跨域访问,您必须将服务器配置为以正确的方式响应该 CORS 预检选项请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM